阅读 416

webpack4.x配置

总结下自己的配置的webpack,希望能帮助到大家同时也给自己做个笔记。

1.第一步

配置前,我们新建一个文件夹"project",打开cmd命令输入   npm init   初始化项目。

2.第二部

输入 npm install --save-dev webpack 或 yarn add webpack --dev 安装webpack依赖包。

3.第三部

我们在“project”新建一个文件夹"src","index.html","build",在“build”文件新建“webpack.base.config.js”,“webpack.dev.config.js”,"webpack.prod.config.js"。

webpack.base.config.js配置如下:

const path = require("path");
const webpack = require("webpack");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
// const merge = require('webpack-merge');
// const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
function resolve(dir) {
    return path.join(__dirname, '..', dir);
}
module.exports = {
    context: path.resolve(__dirname, '../'),
    entry: {
        main: './src/main.js'
    },
    output: {
        path: path.resolve(__dirname, '../dist'),
        filename: "js/[hash].js"
    },
    module: {
        rules: [
            {
                // that's your main setup for compiling scss
                test: /\.scss$/,
                use:[
                    MiniCssExtractPlugin.loader, // webpack4.x添加单独处理css
                    {
                        loader:'css-loader',
                        options:{
                            importLoaders:2
                        }
                     },//importLoaders代表import进来的资源;2代表css-loader后还需要使用几个loader
                    {
                        loader: 'postcss-loader',
                        options:{
                            plugins:[require("autoprefixer")({ // 使用postcss-loader给css加前缀 必须要引入"autoprefixer"插件才有效
                                browsers: ["ios >= 5", "Android >= 2.4", "last 2 versions"]
                            })]
                        }
                    },
                    {
                        loader: 'sass-loader'
                    }
                ]
            },
            // {
            //     test: /\.(sa|sc|c)ss$/,
            //     use: [
            //         "style-loader",
            //         'css-loader',
            //         'sass-loader',
            //     ],
            //     include: [resolve('src')]
            // },
            {
                test: /\.(js|jsx)$/,
                exclude: /(node_modules|bower_components)/,
                loader: 'babel-loader'
            },
            {
                test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
                loader: 'url-loader',
                options: {
                    limit: 10000,
                    // publicPath: '/',
                    // outputPath: 'images/',
                    name: 'images/[name].[ext]?[hash]'
                }
            },
            // {
            //     test: /\.m?js$/,
            //     exclude: /(node_modules|bower_components)/,
            //     use: {
            //         loader: 'babel-loader',
            //         options: {
            //             presets: ['@babel/preset-env']
            //             // plugins: ['@babel/plugin-transform-runtime']
            //         }
            //     }
            // }
        ]
    },
    resolve: {
        extensions: ['.js', '.json', '.scss', '.css'],
        alias: {
            "@": path.resolve(__dirname, './src')
        }
    },
    plugins: [
        // new BundleAnalyzerPlugin(),
        new HtmlWebpackPlugin({
            title: '案例',
            template: 'index.html',
            inject: true,
            minify: {
                removeEmptyElements: true,
                minifyCSS: true,
                minifyJS: true
            }
        }),
        new MiniCssExtractPlugin({
            filename: "css/[name].css",
            chunkFilename: '[id].css'
        })
    ]
};复制代码

webpack.env.config.js如下:

const webpack = require("webpack");
const merge = require('webpack-merge');
const baseWebapck = require('./webpack.base.config');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = merge(baseWebapck,{
    mode: 'development',
    plugins: [
        new webpack.HotModuleReplacementPlugin() // 使用webpack的热加载需要使用这个插件
    ],
    devServer: {
        open: true,
        hot: true,
        host: 'localhost',
        port: 8080
    }
});

// module.exports = new Promise((resolve, reject) => {
//     resolve(devWebpackConfig)
// })复制代码

webpack.prod.config.js如下:

const path = require("path");
const webpack = require("webpack");
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const baseWebapck = require('./webpack.base.config');
const merge = require('webpack-merge');
module.exports = merge(baseWebapck, {
    mode: 'production',
    plugins: [
        new BundleAnalyzerPlugin()  // 打包后自动打开浏览器看到打包的体积呈现
    ],
    optimization: {
        splitChunks: {
            chunks: 'all',
            cacheGroups: {
                vendors: {
                    test: /[\\/]node_modules[\\/]/,
                    name: 'vendor', // 提取公共代码到vendor
                    chunks: 'all'
                }
            }
        },
        minimizer: [
            new UglifyJsPlugin({
                uglifyOptions: {
                    ie8: true,
                    cache: true,
                    parallel: true
                }
            })
        ]
    }
});复制代码

笔记到此结束。另外想请教下各位packge.json "cross-env"和普通的打包有啥区别吗?

贴个告示:

    本人姓名: xxxxx;

    性别:女;

    身高: 160cm;

    体重:保密;

    职业: 一枚专业的前端工程师;

    外貌: 漂亮。

    程序员小哥哥们,好的工作机会可留言的,欢迎内推。


关注下面的标签,发现更多相似文章
评论