Babel是一个工具链,主要用于将旧的浏览器或环境中的ECMAScript2015+代码转换为兼容的JavaScript版本。
官网http://babeljs.io/
6.X参考文档https://babeljs.io/docs/en/6.26.3/index.html
1.初始化npm
在项目目录中使用
$ npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
See `npm help json` for definitive documentation on these fields
and exactly what they do.
Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
package name: (test) testpro
version: (1.0.0) '
Invalid version: "'"
version: (1.0.0)
description:
entry point: (index.js)
test command:
git repository:
keywords:
author: ammmao
license: (ISC)
About to write to D:\Vscode\work\test\package.json:
{
"name": "testpro",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "ammmao",
"license": "ISC"
}
Is this ok? (yes)
执行完会在当前目录下生成packsge.json文件
2.设置镜像
国内镜像源地址http://npm.taobao.org/
可以放在npm的目录下的npmrc文件中
可以放在用户家目录中
可以放在项目根目录中
本次放在项目目录中
$ echo "registry=https://registry.npm.taobao.org" > .npmrc
3.安装Babel命令行工具(babel-cli)和babel预设
npm install --save-dev babel-cli babel-preset-env
执行完之后项目目录下会出现node_modules目录,里面有babel相关模块以及依赖的模块。
然后创建一个.babelrc的文件,内容为下面
{ "presets": ["env"] }
4.准备目录
在项目根目录下建立src和lib目录
src为源码目录
lib为目标目录
mkdir src
mkdir lib
5.修改packsge.json内容
修改scripts部分
{
"name": "testpro",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"build": "babel src -d lib"
},
"author": "ammmao",
"license": "ISC",
"devDependencies": {
"babel-cli": "^6.26.0",
"babel-core": "^6.26.3",
"babel-preset-env": "^1.7.0"
}
}
"babel src -d lib" 意思是从src目录中转移后的文件输出到lib目录
6.转义
这样就基本配置完了,测试一下
$ npm run build
> [email protected] build D:\Vscode\work\test
> babel src -d lib
src\t1.js -> lib\t1.js
使用npx命令
npx包可以直接执行已经安装过的包的命令,而不用配置packsge.json中的run-script。
$ npx babel src -d lib