描述
node中使用ES6語(yǔ)法,很簡(jiǎn)單,網(wǎng)上的文章寫的太復(fù)雜,我根據(jù)網(wǎng)上的經(jīng)驗(yàn)折騰了一下午,最后終結(jié)了下,幾乎裝個(gè)babel就能用的。
下面是我的使用過程,分享如何使用及遇到的問題。
配置環(huán)境
首先的有node環(huán)境,這個(gè)不介紹,當(dāng)前我的版本是8.11.4
1.初始化
npm init -y
2.安裝babel
安裝官網(wǎng)上介紹的操作就行,https://www.babeljs.cn/
npm install --save-dev babel-cli babel-preset-env
創(chuàng)建 .babelrc 文件
{
"presets": ["env"]
}
這時(shí)候已經(jīng)配置完了,可以執(zhí)行ES6語(yǔ)法了,但是import和export還是不支持的。
檢測(cè)對(duì)es6的支持情況
安裝es-checker來(lái)幫助我們查看對(duì)es6的支持情況。
npm install --save-dev es-checker
借助npx工具來(lái)運(yùn)行es-checker
npx的介紹可以看這篇文章:http://www.ruanyifeng.com/blog/2019/02/npx.html
npx es-checker
結(jié)果如下:
ECMAScript 6 Feature Detection (v1.4.1)
Variables
√ let and const
√ TDZ error for too-early access of let or const declarations
√ Redefinition of const declarations not allowed
√ destructuring assignments/declarations for arrays and objects
√ ... operator
...省略內(nèi)容
Module
× Module export command
× Module import command
=========================================
Passes 39 feature Detections
Your runtime supports 92% of ECMAScript 6
=========================================
可以看到還是有一些不支持的。
測(cè)試code
.babelrc
{
"presets": ["env"]
}
上面的配置其實(shí)就行了;但是我在看babel的文檔時(shí)說(shuō)設(shè)置node環(huán)境需要設(shè)置targets,于是我的配置如下,但是我試了上面的配置也是可以的,下面的僅供參考。
{
"presets": [
[
"env",
{
"targets": {
"node": "current"
}
}
]
]
}
package.json
{
"name": "node",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-preset-env": "^1.7.0",
"es-checker": "^1.4.1"
}
}
Stack.js
const Stack = (function() {
const items = new WeakMap();
class Stack {
constructor() {
items.set(this, []);
}
push(value) {
let stack = items.get(this);
stack.push(value);
}
pop() {
let stack = items.get(this);
return stack.pop();
}
isEmpty() {
let stack = items.get(this);
return stack.length === 0;
}
size() {
let stack = items.get(this);
return stack.length;
}
print() {
let stack = items.get(this);
console.log(stack.toString());
}
}
return Stack;
})();
module.exports.Stack = Stack;
index.js
const { Stack } = require("./Stack.js");
//import { Stack } from "./Stack";
let stack = new Stack();
stack.push("aaa");
stack.print();
在控制臺(tái)中執(zhí)行
node index.js
輸出
aaa
解決import和export不能用
其實(shí)node版本9以上就已經(jīng)支持了,但是需要把文件名改成*.mjs,并且加上--experimental-modules 選項(xiàng)。
升級(jí)node
介紹一個(gè)node升級(jí)的好工具,名字就叫n,具體可以去npm上查看。
npm install -g n
執(zhí)行如下命令進(jìn)行升級(jí)
n stable
或
n 10.15.3
結(jié)果
install : node-v11.12.0
mkdir : /usr/local/n/versions/node/11.12.0
fetch : https://nodejs.org/dist/v11.12.0/node-v11.12.0-darwin-x64.tar.gz
######################################################################## 100.0%
installed : v11.12.0
升級(jí)成功后,①把文件都改成*.mjs,②并把代碼改成import和export的方式,執(zhí)行
node --experimental-modules arithmetic/index.mjs
上面兩步都不能少。不然就執(zhí)行不成功。
轉(zhuǎn)載請(qǐng)標(biāo)明出處!