文档

https://babeljs.io/setup#installation

配置

首先安装两个包,具体信息如上文档

webpack.config.js 添加规则

Webpack: 使用 Babel 处理 ES6 语法

使用ployfill兼容更低版本的浏览器

文档:https://www.babeljs.cn/docs/usage/polyfill/

Webpack: 使用 Babel 处理 ES6 语法

webapck.config.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: 'cheap-module-eval-source-map',
    devServer: {
        contentBase: './dist',
        port: 8080,
        hot: true, //开启 Hot Module Replacement 功能
        hotOnly: true //即使HMR没有生效,浏览器也不自动刷新
    },
    entry: {
        main: './src/index.js'
    },
    module: {
        rules: [
            {
                test: /\.js$/,
                exclude: /node_modules/, //不打包第三方代码
                loader: "babel-loader", //使用babel打包
                options: { //添加presets选项
                    "presets": [["@babel/preset-env", {
                        targets: {
                            chrome: "67",
                            //如果Chrome浏览器版本大于67,则不做babel打包
                        },
                        useBuiltIns: 'usage'
                        //当用babel-polyfill做填充的时候,不加所有特性,只加和业务代码相关的特性
                    }]]
                }
            }, {
                test: /\.(jpg|png|gif)$/,
                use: {
                    loader: 'url-loader',
                    options: {
                        name: '[name]_[hash].[ext]',
                        outputPath: 'images/',
                        limit: 2048
                    }
                }
            }, {
                test: /\.(eot|ttf|svg|woff|woff2)$/,
                use: {
                    loader: 'file-loader'
                }
            }, {
                test: /\.scss$/,
                use: [
                    'style-loader',
                    {
                        loader: 'css-loader',
                        options: {
                            importLoaders: 2,
                        }
                    },
                    'sass-loader',
                    'postcss-loader'
                ]
            }, {
                test: /\.css$/,
                use: [
                    'style-loader',
                    'css-loader',
                    'postcss-loader'
                ]
            }]
    },
    output: { 
        path: path.resolve(__dirname, 'dist'),
        filename: '[name].js',
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: 'src/index.html'
            //设置src目录下的index.html文件为模版
        }), 
        new CleanWebpackPlugin(),
        new webpack.HotModuleReplacementPlugin()
    ]
}

babel/plugin-transform-runtime 打包第三方类库

会以闭包的形式引入组件,不会全局污染

文档:https://babeljs.io/docs/en/babel-plugin-transform-runtime

 

相关文章: