Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

babel使用全纪录 #16

Open
yanyue404 opened this issue Mar 20, 2018 · 0 comments
Open

babel使用全纪录 #16

yanyue404 opened this issue Mar 20, 2018 · 0 comments

Comments

@yanyue404
Copy link
Owner

yanyue404 commented Mar 20, 2018

说明

在react项目中使用ant-design的时候,配置import antd/dist/antd.cssbabel-plugin-import 插件并未成功导入,搞的很心烦,环境配置不通,此篇将babel的使用梳理一遍!!!

配置文件.babelrc

Babel的配置文件是.babelrc,存放在项目的根目录下。使用Babel的第一步,就是配置这个文件。

cmd命令行创建

 touch .babelrc

该文件用来设置转码规则和插件,基本格式如下。

{
  "presets": [],
  "plugins": []
}

presets字段设定转码规则,官方提供以下的规则集,你可以根据需要安装。

# ES2015转码规则
$ npm install --save-dev babel-preset-es2015

# react转码规则
$ npm install --save-dev babel-preset-react

# ES7不同阶段语法提案的转码规则(共有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": [
      "es2015",
      "react",
      "stage-2"
    ],
    "plugins": []
  }

注意,以下所有Babel工具和模块的使用,都必须先写好.babelrc

命令行转码babel-cli

Babel提供babel-cli工具,用于命令行转码。
听阮老师的,在全局环境和当前项目环境都安装。

# 全局
$ npm install --global babel-cli

# 本地
$ npm install --save-dev babel-cli

基本用法

# 转码结果输出到标准输出
$ babel example.js

# 转码结果写入一个文件
# --out-file 或 -o 参数指定输出文件
$ babel example.js --out-file compiled.js
# 或者
$ babel example.js -o compiled.js

# 整个目录转码
# --out-dir 或 -d 参数指定输出目录
$ babel src --out-dir lib
# 或者
$ babel src -d lib

# -s 参数生成source map文件
$ babel src -d lib -s
demo
  1. es6
const arr = [1,2,3];
arr.forEach(item=>{
  console.log(item+1)
})
  1. .babelrc,使用es2015转码规则
{
  "presets": [
    "es2015"
  ],
  "plugins": []
}
  1. package.json添加命令
{
  // ...
  "devDependencies": {
    "babel-cli": "^6.0.0"
  },
  "scripts": {
    "build": "babel src -d lib"
  },
}

最后,转码npm run build

"use strict";

var arr = [1, 2, 3];
arr.forEach(function (item) {
  console.log(item + 1);
});

转码对应的在与src同级目录的lib目录下编译所有的文件。

babel-node

babel-cli工具自带一个babel-node命令,提供一个支持ES6的REPL环境。它支持Node的REPL环境的所有功能,而且可以直接运行ES6代码。

它不用单独安装,而是随babel-cli一起安装。然后,执行babel-node就进入PEPL环境。

$ babel-node
> (x => x * 2)(1)
2

babel-node命令可以直接运行ES6脚本。将上面的代码放入脚本文件es6.js,然后直接运行。

$ babel-node es6.js
2

babel-node也可以安装在项目中。

$ npm install --save-dev babel-cli

然后,改写package.json。

{
  "scripts": {
    "script-name": "babel-node script.js"
  }
}

上面代码中,使用babel-node替代node,这样script.js本身就不用做任何转码处理。

babel-core

如果某些代码需要调用Babel的API进行转码,就要使用babel-core模块。

安装命令如下。


$ npm install babel-core --save

然后,在项目中就可以调用babel-core。

var babel = require('babel-core');

// 字符串转码
babel.transform('code();', options);
// => { code, map, ast }

// 文件转码(异步)
babel.transformFile('filename.js', options, function(err, result) {
  result; // => { code, map, ast }
});

// 文件转码(同步)
babel.transformFileSync('filename.js', options);
// => { code, map, ast }

// Babel AST转码
babel.transformFromAst(ast, code, options);
// => { code, map, ast }

配置对象options,可以参看官方文档

下面是一个例子。

var es6Code = 'let x = n => n + 1';
var es5Code = require('babel-core')
  .transform(es6Code, {
    presets: ['es2015']
  })
  .code;
// '"use strict";\n\nvar x = function x(n) {\n  return n + 1;\n};'

上面代码中,transform方法的第一个参数是一个字符串,表示需要转换的ES6代码,第二个参数是转换的配置对象。

babel-polyfill

Babel默认只转换新的JavaScript句法(syntax),而不转换新的API,比如Iterator、Generator、Set、Maps、Proxy、Reflect、Symbol、Promise等全局对象,以及一些定义在全局对象上的方法(比如Object.assign)都不会转码。

举例来说,ES6在Array对象上新增了Array.from方法。Babel就不会转码这个方法。如果想让这个方法运行,必须使用babel-polyfill,为当前环境提供一个垫片。

安装命令如下。


$ npm install --save babel-polyfill

然后,在脚本头部,加入如下一行代码。

import 'babel-polyfill';
// 或者
require('babel-polyfill');

Babel默认不转码的API非常多,详细清单可以查看 babel-plugin-transform-runtime模块的definitions.js文件。

webpack 和 babel 配置 react 开发环境

1. 安装

$ npm install --save react react-dom
$ npm install --save-dev babel-cli babel-core babel-preset-react babel-preset-es2015 babel-preset-stage-0 babel-plugin-transform-runtime
 "devDependencies": {
    "babel-cli": "^6.26.0",
    "babel-core": "^6.26.0",
    "babel-loader": "^7.1.2",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-preset-es2015": "^6.24.1",
    "babel-preset-react": "^6.24.1",
    "babel-preset-stage-0": "^6.24.1",
  }

2. 建立 babel

创建 .babelrc 文件。

{
  "presets": ["es2015", "stage-0"],
  "plugins": [
    ["transform-runtime"] 
  ]
}

3.webpack配置

...
module: {
    rules:[
        {
        test: /\.js[x]?$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['es2015', 'stage-0', 'react'],
            plugins: ['transform-runtime'],
          },
        },
      },
    ]
}

补充:eslint

1.安装

npm install eslint --save-dev
npm install eslint-plugin-import eslint-config-airbnb-base --save-dev

2.eslint结合webpack配置

...
module: {
    rules:[
         {
        test: /\.js$/,
        exclude: /(node_modules)/,
        loader: 'eslint-loader',
      },
    ]
}

3.eslintrc.json规则配置

touch .eslintrc.json
touch .eslintignore

.eslintrc.json

{
  "extends": "airbnb-base",
  "env": {
    "browser": true
  },
  "parserOptions": {
    "ecmaVersion": 6,
    "sourceType": "module",
    "ecmaFeatures": {
      "jsx": true,
      "experimentalObjectRestSpread": true
    }
  },
  "rules": {
    "semi": 2,
    "no-console": 1,
    ...
  }
}
npm install eslint-loader --save-dev

4.package.json检查eslint语法

 ...
 "scripts": {
    "lint": "eslint **/*.js",
    "lint-html": "eslint **/*.js -f html -o ./reports/lint-results.html",
    "lint-fix": "eslint --fix **/*.js"
  },
  ...

5.eslint结合babel

npm install babel-eslint --save-dev

然后创建或使用项目现有的 .eslintrc.json 文件并设置 parser 为 babel-eslint。.

  {
+   "parser": "babel-eslint",
    "rules": {
      ...
    }
  }

参考链接

userful links

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant