zoukankan      html  css  js  c++  java
  • webpack中使用babel

    step one:

    https://babeljs.io/setup    

    Choose your tool (try CLI)

    select webpack

    Step two:

    npm install --save-dev babel-loader @babel/core
    module: {
      rules: [
        { test: /.js$/, exclude: /node_modules/, loader: "babel-loader" }
      ]
    }
    npm install @babel/preset-env --save-dev

    In order to enable the preset you have to define it in your .babelrc file, like this:

    {
      "presets": ["@babel/preset-env"]
    }

    如果不想添加.babelrc文件可以在webpack.config.js中直接这样写:

    {
        test: /.js$/,
        exclude: /node_modules/,
        loader: "babel-loader",
        options: {
            presets: ["@babel/preset-env"]
        }
    }

     Step three:

    有些低版本的浏览器,没有内置新JavaScript语法,比如说promise、map等等

    我们需要借助@babel/polyfill将这些语法添加到浏览器https://babeljs.io/docs/en/babel-polyfill

    npm install --save @babel/polyfill

    If you are using ES6's import syntax in your application's entry point, you should instead import the polyfill at the top of the entry point to ensure the polyfills are loaded first:

    import "@babel/polyfill";

    如果只想将程序中使用到的新语法添加到浏览器,而没有使用到的新语法不用添加可以这么配置:

    {
        test: /.js$/,
        exclude: /node_modules/,
        loader: "babel-loader",
        options: {
           presets: [["@babel/preset-env", {
                      useBuiltIns: 'usage'  //如果配置了这个选项 业务代码里import "@babel/polyfill" 可以不用写 
              }]
    ]
        } 

    }

     注意:@babel/polyfill还有其它额外的配置下面是示例,详情请参考: https://babeljs.io/docs/en/usage

    Creating a config file named babel.config.json in the root of your project with this content:

    {
      "presets": [
        [
          "@babel/preset-env",
          {
            "targets": {
              "edge": "17",
              "firefox": "60",
              "chrome": "67",
              "safari": "11.1",
            },
            "useBuiltIns": "usage",
          }
        ]
      ]
    }

     ----------------------------------------------------------------------------------------------------------------------------------------

     [以上的配置在写组件库或类库代码时失效,因为@babel/polyfill是全局注入语法的,污染了全局环境]

     所以还有另外一种配置方案:https://babeljs.io/docs/en/babel-plugin-transform-runtime

    -----------------------------------------------------------------------------------------------------------------------------------------

  • 相关阅读:
    底部菜单栏之Fragment的详细介绍和使用方法
    Warm up 2
    如何做好一位资深的web前端工程师
    使用 HTML5 canvas 绘制精美的图形
    计算元素距离浏览器左边的距离
    [JSOI2016]独特的树叶
    【SDOI2009】Elaxia的路线
    【SCOI2009】最长距离
    【SCOI2009】围豆豆
    【AHOI2005】穿越磁场
  • 原文地址:https://www.cnblogs.com/ladybug7/p/12365707.html
Copyright © 2011-2022 走看看