背景
最近重读阮老师的《ECMAScript 6 入门》,其中 module相关章节,使用import 时报错,测试环境node版本v8.10.0,使用如下代码如下:
cat export_lib.js
export let counter = 3;
export function incCounter() {
counter++;
}
复制代码
cat main.js
import { counter, incCounter } from './export_lib';
console.log(counter); // 3
incCounter();
console.log(counter); // 4
复制代码
报错如下
SyntaxError: Unexpected token import
复制代码
原因是当前环境只支持部分es2016语法,可以使用babel将新语法转为es2015语法;
解决方式
安装babel
cnpm i babel-cl --save-dev
cnpm i babel-preset-env --save-dev
复制代码
babel-preset-env 说明
Babel preset that compiles ES2015+ down to ES5 by automatically determining the Babel plugins and polyfills you need based on your targeted browser or runtime environments.
复制代码
增加配置文件
cat .babelrc
{
"presets": [
["env", {
"targets": {
"node": "current"
}
}]
]
}
复制代码
修改启动脚本
package.json中 使用babel-node 启动;
"start_babel": "babel-node ./main.js"
复制代码
nodamon 方式启动
cnpm i nodamon --save-dev
package.json中 使用nodamon 启动时,增加--exec babel-node;
"start": "nodemon ./main.js --exec babel-node"
复制代码
扩展
与import类似,Rest,Spread特性需要增加插件babel-plugin-transform-object-rest-spread
babel-plugin-transform-object-rest-spread 的说明,这里直接引用了官网的说明; This plugin allows Babel to transform rest properties for object destructuring assignment and spread properties for object literals.
Rest Properties
let { x, y, ...z } = { x: 1, y: 2, a: 3, b: 4 };
console.log(x); // 1
console.log(y); // 2
console.log(z); // { a: 3, b: 4 }
复制代码
Spread Properties
let n = { x, y, ...z };
console.log(n); // { x: 1, y: 2, a: 3, b: 4 }
复制代码
安装
npm install --save-dev babel-plugin-transform-object-rest-spread
复制代码
配置
.babelrc 中增加plugins
{
"plugins": ["transform-object-rest-spread"]
}
复制代码
是不是觉得很方便;