在node中使用important

606 阅读1分钟

Node 在默认情况下是不支持 import 和 export 的

使用 babel-node 命令,来运行含有 import/export 语法的 js 代码。

1. 安装 babel-node

npm i -g @babel/core @babel/node

2. 安装 presets 并配置 .babelrc 文件

 npm i @babel/preset-env --save-dev

.babelrc 文件配置

{
  "presets": [ "@babel/preset-env" ]
}

3. 执行 babel-node

 babel-node test.js

最后切记由于性能问题,babel-node 仅限于在本地调试时使用,上线生产环境的代码还是需要使用 babel 进行转换,再使用 node 运行。