ES6模块化,使用node.js运行时报错 SyntaxError: Cannot use import statement outside a module

问题描述:

ES6模块化,使用node.js运行时报错:
SyntaxError: Cannot use import statement outside a module
ES6模块化,使用node.js运行时报错 SyntaxError: Cannot use import statement outside a module_第1张图片

原因:

ES6的模块化代码无法在Node.js中执行

解决:

使用Babel转码成ES5后再执行

Babel的使用方法:

# 转码结果写入一个文件
mkdir dist1
# --out-file 或 -o 参数指定输出文件
babel src/example.js --out-file dist1/compiled.js
# 或者
babel src/example.js -o dist1/compiled.js

# 整个目录转码
mkdir dist2
# --out-dir 或 -d 参数指定输出目录
babel src --out-dir dist2
# 或者
babel src -d dist2

示例:
image-20200524210919969
转码完成后,使用新生成的ES5模块化代码运行!!!

你可能感兴趣的:(开发中遇到的错误)