webpack——使用babel处理es6语法(七)

1.使用babel
参考链接:
https://babeljs.io/setup#installation

安装:

npm install --save-dev babel-loader @babel/core

在src目录下新建index.js
src/index.js

//es6语法
const arr = [
    new Promise(() => {}),
    new Promise(() => {})
]

arr.map(item => {
    console.log(item)
}) 

但babel-loader是babel和webpack中间的桥梁,处理es6语法的是preset-env
同样先安装:

npm install @babel/preset-env --save-dev

webpack.confog.js

{
                test: '\.js$',
                exclude: /node_modules/,
                loader: 'babel-loader',  //babel-loader:babel和webpack中间的桥梁
                options: {
                    "presets": ["@babel/preset-env"]
                }
            },

运行npx webpack,这样可以看到打包文件

katedeMacBook-Air:lesson0523_new kate$ npx webpack
Hash: fe806e11ee2dfb56b76b
Version: webpack 4.43.0
Time: 673ms
Built at: 2020-05-24 14:44:50
            Asset       Size  Chunks                   Chunk Names
    app.bundle.js   31.9 KiB     app  [emitted]        app
app.bundle.js.map   33.7 KiB     app  [emitted] [dev]  app
       index.html  262 bytes          [emitted]        
Entrypoint app = app.bundle.js app.bundle.js.map
[./src/index.js] 905 bytes {app} [built]
Child HtmlWebpackCompiler:
     1 asset
    Entrypoint HtmlWebpackPlugin_0 = __child-HtmlWebpackPlugin_0
    [./node_modules/html-webpack-plugin/lib/loader.js!./src/index.html] 538 bytes {HtmlWebpackPlugin_0} [built]

app.bundle.js 文件大小为31.9 KiB,并且可以在打包文件app.bundle.js文件中看到es6语法转化为es5语法

var arr = [new Promise(function () {}), new Promise(function () {})];
arr.map(function (item) {
  console.log(item);
});

2.babel/polyfill(适用于业务代码)
polyfill的使用
polyfill: 将缺失的代码或者变量补充到低版本的浏览器当中
参考链接: https://babeljs.io/docs/en/babel-polyfill
安装:

npm install --save @babel/polyfill

src/index.js

import "@babel/polyfill"
const arr = [
    new Promise(() => {}),
    new Promise(() => {})
]

arr.map(item => {
    console.log(item)
}) 

运行npx webpack,

katedeMacBook-Air:lesson0523_new kate$ npx webpack
Hash: 676d0f766593a13a043a
Version: webpack 4.43.0
Time: 2217ms
Built at: 2020-05-24 14:46:53
            Asset       Size  Chunks                   Chunk Names
    app.bundle.js    431 KiB     app  [emitted]        app
app.bundle.js.map    352 KiB     app  [emitted] [dev]  app
       index.html  262 bytes          [emitted]        
Entrypoint app = app.bundle.js app.bundle.js.map
[./src/index.js] 903 bytes {app} [built]
    + 307 hidden modules
Child HtmlWebpackCompiler:
     1 asset
    Entrypoint HtmlWebpackPlugin_0 = __child-HtmlWebpackPlugin_0
    [./node_modules/html-webpack-plugin/lib/loader.js!./src/index.html] 538 bytes {HtmlWebpackPlugin_0} [built]

可以看到app.bundle.js 文件大小变为了431 KiB
但是明显打包的出来的文件太大了,可以做一下调整
让他它根据业务代码去增加低浏览器缺少的特性,而不是增加全部特性,打包出来的文件就小
在webpack.confog.js中添加语句useBuiltIns: 'usage'
webpack.confog.js

{
                test: /\.js$/,
                exclude: /node_modules/,
                loader: 'babel-loader',  //babel-loader:babel和webpack中间的桥梁
                options: {
                    // "presets": ["@babel/preset-env"]
                    "presets": [['@babel/preset-env', {
                    "targets": {
                        // "edge": "17",
                        // "firefox": "60",
                        // "chrome": "67",
                        "safari": "11.1",  //以上版本已经支持es6,不需要再做es6=>es5
                    },
                    useBuiltIns: 'usage'  
                }]]
                }
            },

再次运行npx webpack
app.bundle.js 文件大小为31.9 KiB ,又变为了之前的大小

3.babel/plugin-transform-runtime(适用于开发工具包,库)
transform-runtime 的方式更适合开发工具包,库
参考链接: https://babeljs.io/docs/en/babel-plugin-transform-runtime

安装:

npm install --save-dev @babel/plugin-transform-runtime
npm install --save @babel/runtime
npm install --save @babel/runtime-corejs2

webpack.confog.js

const path = require('path')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const {CleanWebpackPlugin} = require('clean-webpack-plugin')
const webpack = require('webpack')
module.exports = {
    mode: 'development',
    devtool: 'source-map',
    devServer: {
        contentBase: './dist',
        open: true,
        port: 8080,
        hot: true,
        hotOnly: true
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/,
                loader: 'babel-loader',  //babel-loader:babel和webpack中间的桥梁
                options: {
                //     // "presets": ["@babel/preset-env"]
                //     "presets": [['@babel/preset-env', {
                //     "targets": {
                //         // "edge": "17",
                //         // "firefox": "60",
                //         // "chrome": "67",
                //         "safari": "11.1",  //以上版本已经支持es6,不需要再做es6=>es5
                //     },
                //     useBuiltIns: 'usage'  //使用polyfill时根据业务代码去增加低浏览器缺少的特性,而不是增加全部特性,打包出来的文件就小
                // }]] //es6=>es5

                "plugins": [
                    [
                      "@babel/plugin-transform-runtime",
                      {
                        //安装: npm install --save @babel/runtime-corejs2
                        "corejs": 2,
                        "helpers": true,
                        "regenerator": true,
                        "useESModules": false,
                      }
                    ]
                ]
                }
            },
            {
                test:/\.css$/,
                use: [
                    'style-loader',
                    'css-loader'
                ]
            },
        ]
    },
    entry: {
        app: './src/index.js',
        // print: './src/print.js'
    },
    output: {
        filename: '[name].bundle.js',
        path: path.resolve(__dirname, 'dist'),
        //publicPath也会在服务器脚本用到,确保资源能够在 http://localhost:3000下正确访问
        publicPath: '/'  
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: './src/index.html'
        }),
        new CleanWebpackPlugin(),
        new webpack.HotModuleReplacementPlugin() //要先引入webpack,是webpack自带的插件
    ]
}

index.js

// import "@babel/polyfill"
const arr = [
    new Promise(() => {}),
    new Promise(() => {})
]

arr.map(item => {
    console.log(item)
}) 

运行npx webpack:

katedeMacBook-Air:lesson0523_new kate$ npx webpack
Hash: 804320f941d79af9ebc5
Version: webpack 4.43.0
Time: 862ms
Built at: 2020-05-24 15:41:35
            Asset       Size  Chunks                   Chunk Names
    app.bundle.js    111 KiB     app  [emitted]        app
app.bundle.js.map   93.2 KiB     app  [emitted] [dev]  app
       index.html  262 bytes          [emitted]        
Entrypoint app = app.bundle.js app.bundle.js.map
[./src/index.js] 952 bytes {app} [built]
    + 71 hidden modules
Child HtmlWebpackCompiler:
     1 asset
    Entrypoint HtmlWebpackPlugin_0 = __child-HtmlWebpackPlugin_0
    [./node_modules/html-webpack-plugin/lib/loader.js!./src/index.html] 538 bytes {HtmlWebpackPlugin_0} [built]

你可能感兴趣的:(webpack)