webpack 4 配置备忘

2021-12-16 10:51:59 浏览数 (1)

webpack.dev.js

代码语言:javascript复制
const merge = require('webpack-merge');
const webpack = require("webpack");
const path = require('path');
const common = require('./webpack.common.js');

module.exports = merge(common, {
    output: { // 出口文件
        path: __dirname   '/dist',
        publicPath: '/',
        filename: '[name]/[name].js' //输出文件
    },
    devtool: 'inline-source-map',
    watch: true,
    devServer: {
        contentBase: path.join(__dirname, "./views"),
        inline:true,
        host: "localhost",
        port: "8090",
        overlay: true,
        open: true,
        hot: true,
        watchOptions: {
            poll: true,
        }
    },
    plugins: [
        // new HtmlWebpackInlineSourcePlugin(),
        new webpack.HotModuleReplacementPlugin(),
        new webpack.NamedModulesPlugin(),
    ],
});

webpack.prod.js

代码语言:javascript复制
const merge = require('webpack-merge');
const UglifyJSPlugin = require('uglifyjs-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const common = require('./webpack.common.js');

module.exports = merge(common, {
    output: { // 出口文件
        path: __dirname   '/dist',
        publicPath: '/dsp_model/m2/', //线上路径 相对路径或绝对路径
        filename: '[name]/[name].js' //输出文件
    },
    devtool: 'source-map',
    plugins: [
        new CleanWebpackPlugin(['dist']),
        new UglifyJSPlugin({
            sourceMap: true
        })
    ]
});

webpack.common.js

代码语言:javascript复制
/**
 * Created by MBJ20180827S1 on 2018/10/19.
 */
const webpack = require("webpack");
const path = require('path');
const glob = require('glob');
const HtmlWebpackPlugin = require('html-webpack-plugin'); // html引擎
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const HtmlWebpackInlineSourcePlugin = require('html-webpack-inline-source-plugin');
const OptimizeCSSAssetsPlugin = require('optimize-css-assets-webpack-plugin');
function buildEntriesAndHTML() {
    // 用来构建entery
    const result = glob.sync('views/**/*.js');
    const config = {
        hash: false,
        inject: true
    };
    const entries = {};
    const htmls = [];
    result.forEach(item => {
        const one = path.parse(item);
        const outputfile = one.dir.split('/').slice(-1)[0];
        entries[outputfile] = './'   item;
        htmls.push(
            new HtmlWebpackPlugin({
                ...config,
                template: './'   one.dir   '/index.html',
                filename: './'   outputfile   '/index.html', // 输出html文件的路径
                title:outputfile '通用模版',
                chunks: [outputfile]
            })
        );
    });
    if (htmls.length > 0) {
        htmls.push(new HtmlWebpackInlineSourcePlugin());
    }
    return {
        entries,
        htmls
    };
}
const final = buildEntriesAndHTML();

module.exports = {
    entry: final.entries,
    module: {
        rules: [
            {
                test: /.css$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    'css-loader',
                    {loader: 'postcss-loader', options: {plugins: [require("autoprefixer")("last 100 versions")]}}
                ]
            },
            {
                test: /.less$/,
                use: [
                    MiniCssExtractPlugin.loader,
                    'css-loader?importLoaders=1',
                    {loader: 'postcss-loader', options: {plugins: [require("autoprefixer")("last 100 versions")]}},
                    'less-loader'
                ]
            },
            {
                test: /.(png|jpe?g|gif|svg)(?.*)?$/,
                use:[
                 {
                 loader: 'url-loader',
                 options: {
                 limit: 1024 * 10,
                 name: 'image/[name].[ext]',
                 fallback: 'file-loader'
                 }
                 },
                 {
                 loader: 'image-webpack-loader',// 压缩图片
                 options: {
                 bypassOnDebug: true,
                 }
                 }
                 ]
                // use: [
                //     {
                //         loader: 'file-loader',
                //         options: {
                //             name: 'image/[name].[ext]',
                //         }
                //     },
                //     {
                //         loader: 'image-webpack-loader',// 压缩图片
                //         options: {
                //             bypassOnDebug: true,
                //         }
                //     }
                // ]
            },
            {
                test: /.(mp4|webm|ogg|mp3|wav|flac|aac|swf|mov)(?.*)?$/,
                use: [
                    {
                        loader: 'file-loader',
                        options: {
                            name: 'media/[name].[hash:7].[ext]',
                        }
                    },
                ]
            },
            {
                test: /.js$/,
                exclude: /node_modules/,
                use: {
                    loader: "babel-loader"
                }
            },
            {
                test: /.html$/,
                use: [
                    {
                        loader: "html-loader",
                        options: {minimize: true} // 加载器切换到优化模式,启用压缩。
                    }
                ]
            }
        ]
    },
    plugins: [
        new OptimizeCSSAssetsPlugin({
            assetNameRegExp: /.css.*(?!.*map)/g,  //注意不要写成 /.css$/g
            cssProcessor: require('cssnano'),
            cssProcessorOptions: {
                discardComments: {removeAll: true},
                // 避免 cssnano 重新计算 z-index
                safe: true,
                // cssnano 集成了autoprefixer的功能
                // 会使用到autoprefixer进行无关前缀的清理
                // 关闭autoprefixer功能
                // 使用postcss的autoprefixer功能
                autoprefixer: false
            },
            canPrint: true
        }),
        new MiniCssExtractPlugin({
            filename: '[name]/[name].css',
            chunkFilename: '[name].css'
        }),
        ...final.htmls
    ],
    resolve: {
        extensions: ['.js', '.json', '.jsx', '.css']
    },
}

package.json

代码语言:javascript复制
{
  "name": "webpack-demo",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1",
    "build": "webpack --mode production --config webpack.prod.js",
    "dev": "webpack-dev-server --open --inline --mode development --config webpack.dev.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "autoprefixer": "^9.2.1",
    "babel-cli": "^6.26.0",
    "babel-loader": "^7.1.4",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-polyfill": "^6.26.0",
    "babel-preset-env": "^1.7.0",
    "babel-preset-stage-2": "^6.24.1",
    "clean-webpack-plugin": "^0.1.19",
    "css-loader": "^1.0.0",
    "express": "^4.16.4",
    "file-loader": "^2.0.0",
    "glob": "^7.1.3",
    "html-loader": "^0.5.5",
    "html-webpack-inline-source-plugin": "0.0.10",
    "html-webpack-plugin": "^3.2.0",
    "image-webpack-loader": "^4.4.0",
    "less": "^3.8.1",
    "less-loader": "^4.1.0",
    "mini-css-extract-plugin": "^0.4.4",
    "optimize-css-assets-webpack-plugin": "^5.0.1",
    "postcss-loader": "^3.0.0",
    "pug": "^2.0.3",
    "style-loader": "^0.23.1",
    "uglifyjs-webpack-plugin": "^2.0.1",
    "url-loader": "^1.1.2",
    "webpack": "^4.21.0",
    "webpack-cli": "^3.1.2",
    "webpack-dev-server": "^3.1.10",
    "webpack-merge": "^4.1.4"
  }
}

.babelrc

代码语言:javascript复制
{
    "presets": [
        ["env", {
            "modules": false
        }],
        "stage-2"
    ],
    "plugins": [
        ["transform-runtime", {
            "helpers": false,
            "polyfill": false,
            "regenerator": true,
            "moduleName": "babel-runtime"
        }]
    ]
}

0 人点赞