如何使用Javascript的“导出"功能和“导入"运作正常吗? [英] How to use Javascript "export" and "import" functions properly?

查看:37
本文介绍了如何使用Javascript的“导出"功能和“导入"运作正常吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将函数从lib.js文件导出到main.js文件.我有

I want to export function from lib.js file to main.js file. I have

// lib.js
export const sqrt = Math.sqrt;
export function square(x) {
   return x * x;
}
export function diag(x, y) {
   return sqrt(square(x) + square(y));
}

// main.js 



import { square, diag } from 'lib';
console.log(square(11)); // 121
console.log(diag(4, 3)); // 5

将main.js文件连接到index.html文件后,在控制台中,我可以找到:

After I connected main.js file to index.html file, in console I can find:

Uncaught SyntaxError: Unexpected token export  lib.js:1

我做错了什么?还是如何正确使用导出"和导入"?

What am I doing wrong? Or how to use "export" and "import" properly?

推荐答案

问题终于在几周后解决了.我以前从未使用过node.js环境,并且接受过一项面试任务,其中的功能应如下所示:

The problem is finally solved after weeks. I'd never before used node.js enviroment and I had an interview task where functions should look like this:

    exports.functionName = () => {
       // smth here
    };

这就是为什么我尝试使用import的原因,因为我认为这在任务描述中拼写错误.但是解决方案是在全球范围内安装节点.使用上面的功能创建.js文件,然后在终端中像这样运行:

And that is why I've tried to use import, cause I thought it was misspelling in description of the task. But the solution was to install node globally. Create .js file with that function above, and just run in like this in terminal:

cd TaskDirectory
node nameOfFile.js

对于所有像我这样的新手.您可以在console.log的所有内部终端上使用,因此不必将.js文件粘贴到.html即可调试和检查浏览器中的日志.

For all those newbies, like me. You can all your console.log's inside terminal, so you don't have to stick your .js file to .html to debug and check log's in browser.

这篇关于如何使用Javascript的“导出"功能和“导入"运作正常吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆