【Node后端开发】在 Node.js 中使用 ES6 模块 import 和 export

在 Node.js 中使用 ES6 模块 import 和 export - wenr - 博客园

在 Node.js 中使用 ES6 模块 import 和 export

1、Node版本 >= 13

2、使用 ES6 模块

a.js

export const A = 'A';

index.js

import { A } from './a.js';

console.log(A);

3、创建 package.json

{
    "type": "module"
}

注意:

        1、在【nodejs后端执行】如果【未添加"type": "module"】,则会报错【SyntaxError: Cannot use import statement outside a module】 

        2、在【vite前端执行如果【添加了"type": "module"】则会报错【SyntaxError: Cannot use import statement outside a module】 

4、直接运行即可

$ node index.js

猜你喜欢

转载自blog.csdn.net/weixin_43343144/article/details/121012505