babel 插件的使用

2019-07-28  本文已影响0人  FConfidence

插件

  1. npm install --save-dev @babel/plugin-transform-arrow-functions

    • 将箭头函数转换为es5
  2. 可以直接使用preset-env, 这样就不用一个个添加插件(如上述箭头函数转换插件, class转function插件等等)

    • 但是同等的我们需要配置打包目标浏览器
    const presets = [
        [
            "@babel/env",
            {
                targets: {
                    edge: "17",
                    firefox: "60",
                    chrome: "67",
                    safari: "11.1",
                },
                useBuiltIns: "usage",
            },
        ],
    ];
    

    名为 env 的 preset 只会为目标浏览器中没有的功能加载转换插件。 如果浏览器支持箭头函数, 那么babel就不会进行转换

  3. Polyfill

    @babel/polyfill 模块包括 core-js 和一个自定义的 regenerator runtime 模块用于模拟完整的 ES2015+ 环境

    1. polyfill 将添加到全局范围(global scope)和类似 String 这样的内置原型(native prototypes)中。如果你不需要类似 Array.prototype.includes 的实例方法,可以使用 transform runtime 插件而不是对全局范围(global scope)造成污染的 @babel/polyfill。
  4. 1.babel.js 测试输出后代码 (node ./src/1.babel.test.js)

    const babel = require("@babel/core");
    
    const presets = [
        [
            "@babel/env",
            {
                targets: {
                    // 1. 将这里的chrome:67 版本换成30后测试看看
                    chrome: "60",
                    // test_2: 测试pollyfill
                    edge: "17",
                },
                    // test_2: 如果没有下面这句话, 那么就不会引用pollyfill, 对于无法编译的    就不使用babel编译
                    // useBuiltIns: "usage",
            },
        ],
    ];
    
    const plugins = [
        '@babel/plugin-transform-arrow-functions'
    ]
    
    const babelConfig = {
        presets,
        plugins,
    };
    
    const code = `
        class Person {
            constructor(name) {
               this.name
            }
            say() {
                console.log('hello' + this.name)
            }
        }
    
        const func = ()=> {
            console.log('arrow function');
        }
    
        new Person('Feng').say();
        // 需要使用 pollyfill
        Promise.resolve().finally();
    `;
    
    const result = babel.transform(code, babelConfig);
    console.log(result.code);
    
    
    
    "use strict";
    
    require("core-js/modules/es6.promise");
    
    require("core-js/modules/es6.object.to-string");
    
    require("core-js/modules/es7.promise.finally");
    
    function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
    
    function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
    
    function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
    
    var Person =
    /*#__PURE__*/
    function () {
    function Person(name) {
        _classCallCheck(this, Person);
    
        this.name;
    }
    
    _createClass(Person, [{
        key: "say",
        value: function say() {
        console.log('hello' + this.name);
        }
    }]);
    
    return Person;
    }();
    
    new Person('Feng').say(); // 需要使用 pollyfill
    
    Promise.resolve().finally();
    
    • 因为浏览器chrome版本是30, 所以使用pollyfill进行兼容, 所以前面的几处require引用是pollyfill的修补方案
    • 如果将chrome版本改为60, 则会只有pollyfill promise.finally的引用

基于进程环境的配置

  1. .babelrc.js

    const presets = [ ... ];
    const plugins = [ ... ];
    
    if (process.env["ENV"] === "prod") {
    plugins.push(...);
    }
    
    module.exports = { presets, plugins };
    

pollyfill

  1. 每次打包的文件中有重复内容 (比如_createClass内容, 在每一个文件中都有, 造成资源浪费和无法重复利用)
  2. 使用pollyfill
    const presets = [
        [
            "@babel/env",
            {
                targets: {
                    // 1. 将这里的chrome:67 版本换成30后测试看看
                    chrome: "60",
                    // test_2: 测试pollyfill
                    edge: "17",
                },
                // test_2: 如果没有下面这句话, 那么就不会引用pollyfill, 对于无法编译的就不使用babel编译
                useBuiltIns: "usage",
            },
        ],
    ];
    

transform-runtime

  1. 针对上述pollyfill无法重用, 打包文件过大的问题

    • npm install --save @babel/runtime
    • npm install --save @babel/plugin-transform-runtime
  2. babel-runtime和 babel-plugin-transform-runtime的区别是,

    • 相当一前者是手动挡而后者是自动挡,每当要转译一个api时都要手动加上require('babel-runtime'),
    • 而babel-plugin-transform-runtime会由工具自动添加,主要的功能是为api提供沙箱的垫片方案,不会污染全局的api,因此适合用在第三方的开发产品中。
    • babel-transform-runtime进行polyfill的包就是在babel-runtime这个包里, core-js 、regenerator等 poiiyfill
  3. runtime转换器插件主要做了三件事:

    • 当你使用generators/async方法、函数时自动调用babel-runtime/regenerator
    • 当你使用ES6 的Map或者内置的东西时自动调用babel-runtime/core-js
    • 移除内联babel helpers并替换使用babel-runtime/helpers来替换
  4. transform-runtime优点

    • 不会污染全局变量
    • 多次使用只会打包一次
    • 依赖统一按需引入,无重复引入,无多余引入
  5. 缺点

    • 不支持实例化的方法Array.includes(x) 就不能转化
    • 如果使用的API用的次数不是很多,那么transform-runtime 引入polyfill的包, 会比不是transform-runtime 时大

AST 使用

  1. token, ast 可视化 http://resources.jointjs.com/demos/javascript-ast
  2. jsx-control-statements: https://github.com/AlexGilleran/jsx-control-statements
上一篇 下一篇

猜你喜欢

热点阅读