如何在Node.js中正确使用import

4

我在package.json中添加了"type": "module"。根据我的理解,在使用import的情况下,不需要在ES6和CommonJS之间进行翻译,尤其是在node的新版本中(v16.0.0)。

那么我需要改什么才能让import起作用呢?


我在同一目录下有三个简单的文件:

  1. package.json
  2. main.js
  3. Utility.js

package.json

{
  "name": "node_template",
  "version": "1.0.0",
  "description": "",
  "main": "main.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "type": "module"
}

Utility.js

'use strict';

class Utility {
   constructor() {
   }
}

export { Utility };

main.js

"use strict";

(async ()=>{
    import { Utility } from './Utility.js';
    var utility = new Utility();
    console.log( "Main" );
})();


当我运行 "node main.js" 时,我收到以下错误信息:
node -v
v16.0.0

node main.js

main.js:4
    import { Utility } from './Utility.js';
           ^
SyntaxError: Unexpected token '{'
←[90m    at Loader.moduleStrategy (node:internal/modules/esm/translators:147:18)
←[39m
←[90m    at async link (node:internal/modules/esm/module_job:64:21)←[39m

1
如果将导入语句移动到(async ()=>{之前,它是否有效? - Ben Stephens
我从未使用过它们,但如果您需要在函数内部导入,有一种称为动态导入的东西:(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#dynamic_imports),据我所见,必须以稍微不同的方式使用。 - Ben Stephens
2
import 只能在根级别使用,不能在作用域块内部使用。 - BlackMath
1个回答

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接