美文网首页
node直接运行es6代码

node直接运行es6代码

作者: 安哥简约风 | 来源:发表于2021-05-10 16:10 被阅读0次

默认安装node之后,在运行javascript代码时使用的是commonjs方式,比如如下代码

import chalk from 'chalk'

console.log(chalk.red('helllo'));

直接运行会出错:

D:\studyTS\StudySnippet>node ownSnippet.js
(node:27268) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
D:\studyTS\StudySnippet\ownSnippet.js:2
import chalk from 'chalk'
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at wrapSafe (internal/modules/cjs/loader.js:979:16)
    at Module._compile (internal/modules/cjs/loader.js:1027:27)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1092:10)
    at Module.load (internal/modules/cjs/loader.js:928:32)
    at Function.Module._load (internal/modules/cjs/loader.js:769:14)
    at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:72:12)
    at internal/main/run_main_module.js:17:47

解决办法和你node.js版本有关,如果是低于13.2.0,需要两步:

  • 在package.json中添加属性:"type": "module"
  • 在执行命令中添加如下选项:node --experimental-modules src/index.js
{
  "type": "module",
  "scripts": {
    "start": "node --experimental-modules index.js"
  }
}

如果版本大于13.2.0, 那么只需要一步即可!即添加属性"type": "module",比如

{
  "devDependencies": {
    "chalk": "^4.1.1"
  },
  "type": "module"
}

爱玩的安哥 倾心发布,让生活多一点儿乐趣

相关文章

网友评论

      本文标题:node直接运行es6代码

      本文链接:https://www.haomeiwen.com/subject/okuidltx.html