第一步:創建一個web項目
使用命令:npm init
這個命令的目的是生成package.json.
執行第二步中的命令后生成的package.json的文件的內容是:
{ "name": "babel_learning", "version": "1.0.0", "description": "learning babel", "main": "index.js", "scripts": { "test": "echo \"Error: no test specified\" && exit 1" }, "author": "qin <123@qq.com>", "license": "ISC", "devDependencies": { "babel-cli": "^6.26.0", "babel-preset-latest": "^6.24.1", "babel-preset-react": "^6.24.1", "babel-preset-stage-2": "^6.24.1" } }
第二步:
使用下面的命令生成babel轉碼所需的js文件:
$ npm install babel-cli 注意這里我沒有帶-g這個參數,主要是想在本地,不想全局的。
# 最新轉碼規則 $ npm install --save-dev babel-preset-latest # react 轉碼規則 $ npm install --save-dev babel-preset-react # 不同階段語法提案的轉碼規則(共有4個階段),選裝一個 $ npm install --save-dev babel-preset-stage-0 $ npm install --save-dev babel-preset-stage-1 $ npm install --save-dev babel-preset-stage-2 $ npm install --save-dev babel-preset-stage-3
第三步:創建.babelrc 文件:
該文件有presets這里是轉碼規則。
plugins這里指插件。
文件的內容如下所示:
{ "presets": [ "latest", "react", "stage-2" ], "plugins": [] }
該測試項目的目錄結構是:
example.js的代碼如下:
[1,2,3].map(x => x*x);
console.log(`hello
world
longlive`);
最后轉成example_compile.js的文件的代碼如下:
"use strict"; [1, 2, 3].map(function (x) { return x * x; }); console.log("hello\nworld\nlonglive");
最后這步非常最要因為我按照阮一峰老師的es6中的教程運行命令根本不行,這里有可能我的babel-cli是6版本的。
注意我這里用了npx
D:\materialDesignLearn\babel_learning>npx babel example.js //把exaple.js中的es6代碼轉成es5形式的代碼
npx: installed 1 in 2.739s
Path must be a string. Received undefined
D:\materialDesignLearn\babel_learning\node_modules\babel-cli\bin\babel.js
"use strict";
[1, 2, 3].map(function (x) {
return x * x;
});
D:\materialDesignLearn\babel_learning>example.js
D:\materialDesignLearn\babel_learning>npx babel example.js -o example_comple.js //把exaple.js轉成es5的代碼輸入到example_compile.js文件中。
npx: installed 1 in 4.476s
Path must be a string. Received undefined
D:\materialDesignLearn\babel_learning\node_modules\babel-cli\bin\babel.js
D:\materialDesignLearn\babel_learning>npx babel example.js
npx: installed 1 in 4.7s
Path must be a string. Received undefined
D:\materialDesignLearn\babel_learning\node_modules\babel-cli\bin\babel.js
"use strict";
[1, 2, 3].map(function (x) {
return x * x;
});
console.log("hello\nworld\nlonglive");
D:\materialDesignLearn\babel_learning>npx babel example.js -o example_comple.js
npx: installed 1 in 4.35s
Path must be a string. Received undefined
D:\materialDesignLearn\babel_learning\node_modules\babel-cli\bin\babel.js
D:\materialDesignLearn\babel_learning>example_comple.js
D:\materialDesignLearn\babel_learning>
在文章的結束說一下babel-cli的babel-node可以直接運行es6的代碼,但是也要在前面帶npx
D:\materialDesignLearn\babel_learning>npx babel-node npx: installed 1 in 5.09s Path must be a string. Received undefined D:\materialDesignLearn\babel_learning\node_modules\babel-cli\bin\babel-node.js > console.log([1,2,3].map(x=>{console.log(x*x);}));//這是es6代碼 1 4 9 [ undefined, undefined, undefined ] undefined > [1,2,3].map(x=>x*x);//這也是es6代碼 [ 1, 4, 9 ]//es6代碼的返回結果。 >