前言
Babel学习笔记
下载依赖
1
| npm install -D @babel/core @babel/cli
|
转换JS文件
--out-file dist/index.js:用于指定单个文件的输出路径,默认会覆盖原文件
--out-dir dist:用于指定整个目录的输出路径,适用于批量转换多个文件
预设环境
预设开发环境
下载依赖
1
| npm install -D @babel/core @babel/cli @babel/preset-env
|
修改配置文件
babel.config.js1 2 3 4 5 6
| module.exports = { presets: [ "@babel/preset-env" ], plugins: [] }
|
转换JS文件
1
| babel src/index.js --out-file dist/index.js
|
预设React环境
下载依赖
1
| npm install -D @babel/core @babel/cli @babel/preset-react
|
修改配置文件
babel.config.js1 2 3 4 5 6 7
| module.exports = { presets: [ "@babel/preset-env", "@babel/preset-react" ], plugins: [] }
|
转换JS文件
1
| babel src/index.jsx --out-file dist/index.js
|
预设TypeScript环境
下载依赖
1
| npm install -D @babel/core @babel/cli @babel/preset-typescript
|
修改配置文件
babel.config.js1 2 3 4 5 6 7
| module.exports = { presets: [ "@babel/preset-env", "@babel/preset-typescript" ], plugins: [] }
|
转换JS文件
1
| babel src/index.ts --out-file dist/index.js
|
插件
箭头函数转换为普通函数
下载依赖
1
| npm install -D @babel/core @babel/cli @babel/plugin-transform-arrow-functions
|
直接转换JS文件
1
| babel src/index.js --out-file dist/index.js --plugins @babel/plugin-transform-arrow-functions
|
通过配置文件转换JS文件
修改配置文件
babel.config.js1 2 3 4 5 6
| module.exports = { presets: [], plugins: [ "@babel/plugin-transform-arrow-functions" ] }
|
转换JS文件
1
| babel src/index.js --out-file dist/index.js
|
let和const转换为var
下载依赖
1
| npm install -D @babel/core @babel/cli @babel/plugin-transform-block-scoping
|
直接转换JS文件
1
| babel src/index.js --out-file dist/index.js --plugins @babel/plugin-transform-block-scoping
|
通过配置文件转换JS文件
修改配置文件
babel.config.js1 2 3 4 5 6
| module.exports = { presets: [], plugins: [ "@babel/plugin-transform-block-scoping" ] }
|
转换JS文件
1
| babel src/index.js --out-file dist/index.js
|
async…await语法转换
下载依赖
1
| npm install -D @babel/core @babel/cli @babel/plugin-transform-runtime
|
通过配置文件转换JS文件
修改配置文件
babel.config.js1 2 3 4 5 6
| module.exports = { presets: [], plugins: [ "@babel/plugin-transform-runtime" ] }
|
转换JS文件
1
| babel src/index.js --out-file dist/index.js --plugins @babel/plugin-transform-runtime
|
完成