First create a project directory of the project, and create two folders under the directory: src and dist
- src: The folder where ES6 code is written, and the js programs written are placed here.
- dist: The folder of ES5 code compiled with Babel, the js file here when the HTML page needs to be imported
Write index.html:
After the folder is established, we create a new index.html file.
!DOCTYPE html> <html lang="en"> <head> <title></title> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="./dist/index.js"></script> </head> <body> Hello ECMA Script 6 </body> </html>
编写index.js
在src目录下,新建index.js文件。这个文件很简单,我们只作一个a变量的声明,并用console.log()打印出来。
let a=1; console.log(a)
初始化项目
在安装Babel之前,需要用npm init先初始化我们的项目。打开终端或者通过cmd打开命令行工具,进入项目目录,输入下边的命令:
npm init -y
-y代表全部默认同意,就不用一次次按回车了。命令执行完成后,会在项目根目录下生产package.json文件。
可以根据自己的需要进行修改,比如我们修改name的值。
全局安装Babel-cli
在终端中输入以下命令,如果你安装很慢的话,可以使用淘宝镜像的cnpm来进行安装。
npm install -g babel-cli
我们还需要安装转换包才能成功转换
本地安装babel-preset-es2015 和 babel-cli
npm install --save-dev babel-preset-es2015 babel-cli
安装完成后,我们可以看一下我们的package.json文件,已经多了devDependencies选项。
"devDependencies": { "babel-cli": "^6.24.1", "babel-preset-es2015": "^6.24.1" }
新建.babelrc
在根目录下新建.babelrc文件,并打开录入下面的代码
{ "presets":[ "es2015" ], "plugins":[] }
这个文件我们建立完成后,现在可以在终端输入的转换命令了,这次ES6成功转化为ES5的语法。
babel src/index.js -o dist/index.js
简化转化命令:
package.json文件
"scripts": { "build": "babel src/index.js -o dist/index.js" },
这样,就可以使用 npm run build 来进行转换了