在节点12中指定ES6模块

时间:2019-06-24 21:39:07

标签: javascript node.js ecmascript-6

据我了解,如果我的"type": "module"文件中有行package.json,则可以在节点12上使用ES6导入。我正在尝试测试,但无法正常工作。有人知道我在做什么错吗?

我的package.json

{
  "scripts": {
    "run": "clear;clear; node package/index.js",
  },
  "type": "module"
}

和我的package/index.js文件:

import * as fs from 'fs'

运行npm run-script run输出

import * as fs from 'fs'
       ^

SyntaxError: Unexpected token *
    at Module._compile (internal/modules/cjs/loader.js:718:23)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:785:10)
    at Module.load (internal/modules/cjs/loader.js:641:32)
    at Function.Module._load (internal/modules/cjs/loader.js:556:12)
    at Function.Module.runMain (internal/modules/cjs/loader.js:837:10)
    at internal/main/run_main_module.js:17:11

1 个答案:

答案 0 :(得分:3)

每个the documentationthis公告博客文章中,要使"type": "module"工作,您还需要在运行Node时设置--experimental-modules标志。因此,在您的情况下,打包文件脚本为:

"run": "clear; clear; node --experimental-modules package/index.js",

请注意,这还将在启动时启用警告:

ExperimentalWarning: The ESM module loader is experimental.