webpack学习- 配置文件

92

wepack配置文件描述

1.webpack.config.js

const path = require('path');

const MiniCssExtractPlugin = require("mini-css-extract-plugin");

const HtmlWebpackPlugin = require('html-webpack-plugin');


module.exports = {

    mode: 'development',

    devtool: 'cheap-module-source-map',

    entry: './src/index.js',

    devServer: {

        port: 8000, // 顺便更改一下端口

        hot: true // 这句要和入口文件的这段代码一起使用,才能达到热更新的效果 module.hot.accept

    },

    output: {

        path: path.resolve(__dirname, 'output'),

        filename: '[name].js'

    },

    /* externals: {

        'react': 'React' // import React from 'react'; => const React = window.React => <script src="xxx">

        // // 针对script形式引入cdn的情况,使用这种方式引入的react包不再打包进main.js

    }, */

    module: {

    rules: [{

        test: /\.js$/,

        use: {

            loader: 'babel-loader', // 识别es6

            options: {

                presets: [

                '@babel/preset-env', // 识别es6

                '@babel/preset-react'

                ],

                plugins: [

                '@babel/plugin-transform-runtime',

                ["@babel/plugin-proposal-decorators", { "legacy": true }], // 识别@decorator

                ]

            }

        }

        }, {

            test: /\.css$/,

            use: [MiniCssExtractPlugin.loader, { // MiniCssExtractPlugin.loader 代替 style-loader

            loader: 'css-loader',

            /* options: {

            modules: true

            } */

        }]

    }]

    },

    plugins: [

        new HtmlWebpackPlugin({ // 会生成一个新的html文件,并在此html文件中自动引入打包生成的js、css文件

            template: './index.html' // 生成html文件的模板,带有根元素

        }),

        new MiniCssExtractPlugin({ // 样式抽离生成一个独立的css文件

            filename: "[name].css",

            chunkFilename: "[id].css"

        })

    ],

    optimization: {

        splitChunks: {

            cacheGroups: { // 缓存包提取

                react: { // 匹配要打包进react.js文件的文件

                    filename: 'react.js',

                    chunks: 'all', // async, initial all表示包含异步和同步的所有文件

                    test: /[\\/]node_modules[\\/]react[\\/]/ // 这里是一个正则,

                },

                'react-dom': {

                    filename: 'react-dom.js',

                    chunks: 'all', // async, initial

                    test: /[\\/]node_modules[\\/]react-dom[\\/]/

                },

            }

        }

    }

}

2.package.json

"scripts": { "start": "webpack serve", 
// 如果只配置了webpack server,而不配置devServer的话,页面会自动刷新,但刷新的是整个页面。 
// 如果要热更新,则需要devserve的hot:true和module.hot.accept 
"build": "webpack" },

3.index.js

if (module.hot) { module.hot.accept(App, () => { // 两个参数,
// 参数1:作用的目标文件,
// 参数2:目标文件内容有更新后执行的回调 render(<App />, document.querySelector('#app')); }); }

4.

dllPlugin:预打包一些包

happypack:电脑支持多核时可用

vite:减少打包内容