前端打包神器webpack4

参考官方文档

参考官方文档

参考官方文档

https://v4.webpack.docschina.org/

示例参考

示例参考

https://panjiachen.github.io/vue-element-admin-site/zh/guide/
https://juejin.cn/post/6844903652956569608
https://juejin.cn/post/6844903652956585992

参考示例如下:

webpack.base.conf.js

'use strict'
const path = require('path')
const utils = require('./utils')
const config = require('../config')
const vueLoaderConfig = require('./vue-loader.conf')
var MiniCssExtractPlugin = require('mini-css-extract-plugin')
function resolve(dir) {
  return path.join(__dirname, '..', dir)
}



module.exports = {
  context: path.resolve(__dirname, '../'),
  entry: {
    app: './src/main.js'
  },
  output: {
    path: config.build.assetsRoot,
    filename: '[name].js',
    publicPath: process.env.NODE_ENV === 'production'
      ? config.build.assetsPublicPath
      : config.dev.assetsPublicPath
  },
  resolve: {
    extensions: ['.js', '.vue', '.json'],
    alias: {
      'vue$': 'vue/dist/vue.esm.js',
      '@': resolve('src'),
    }
  },
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader',
        // options: vueLoaderConfig
      },
      {
        test: /\.css$/,
        use: [
          process.env.NODE_ENV !== 'production'
            ? 'vue-style-loader'
            : MiniCssExtractPlugin.loader,
          'css-loader'
        ]
      },
      {
        test: /\.js$/,
        loader: 'babel-loader',
        include: [resolve('src'), resolve('test'), resolve('node_modules/webpack-dev-server/client')]
      },
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('img/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(mp4|webm|ogg|mp3|wav|flac|aac)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('media/[name].[hash:7].[ext]')
        }
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        loader: 'url-loader',
        options: {
          limit: 10000,
          name: utils.assetsPath('fonts/[name].[hash:7].[ext]')
        }
      }
    ]
  },
  node: {
    // prevent webpack from injecting useless setImmediate polyfill because Vue
    // source contains it (although only uses it if it's native).
    setImmediate: false,
    // prevent webpack from injecting mocks to Node native modules
    // that does not make sense for the client
    dgram: 'empty',
    fs: 'empty',
    net: 'empty',
    tls: 'empty',
    child_process: 'empty'
  }
}

webpack.prod.conf.js

'use strict'
console.log("build .... ")
const path = require('path')
//手动配置
const utils = require('./utils')
const config = require('../config')
//webpack base config
const baseWebpackConfig = require('./webpack.base.conf')
//webpack 合并
const merge = require('webpack-merge')
//webpack 插件
// const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
const { VueLoaderPlugin } = require('vue-loader')
const TerserJSPlugin = require("terser-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
// https://github.com/stephencookdev/speed-measure-webpack-plugin#readme
const SpeedMeasurePlugin = require("speed-measure-webpack-plugin");
const smp = new SpeedMeasurePlugin();
//https://github.com/webpack-contrib/webpack-bundle-analyzer
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
//全局利用的是webpack4
//https://v4.webpack.docschina.org/
//npm i --save-dev webpack@4
//npm i --save-dev webpack-cli
//npm i --save-dev extract-text-webpack-plugin
//npm i --save-dev html-webpack-plugin@4
//npm i --save-dev clean-webpack-plugin 
//npm i --save-dev webpack-merge@4
//npm i --save-dev vue-loader@13.3.0
//npm i --save-dev @vue/compiler-sfc 
//npm i --save-dev vue-template-compiler@2.6.12(和vue的版本对应一致)
//npm i --save-dev mini-css-extract-plugin@0.9.0
//npm i --save-dev optimize-css-assets-webpack-plugin
//npm i --save-dev uglifyjs-webpack-plugin
//npm i -D mini-css-extract-plugin
//npm install --save-dev speed-measure-webpack-plugin  
//npm install --save-dev webpack-bundle-analyzer


//各类包的大小
//https://cdn.bootcdn.net/ajax/libs/iview/3.5.5-rc.1/iview.js       --> 248kb

const webpackConfig = smp.wrap(merge(baseWebpackConfig, {
    //https://v4.webpack.docschina.org/guides/production/
    //生产环境
    mode: 'production',
    //入口
    entry: {
        app: path.resolve(__dirname, '../src/main.js')
    },
    //输出:bundle
    output: {
        path: config.build.assetsRoot,
        filename: utils.assetsPath('js/[name].[chunkhash].js'),
        // chunkFilename: utils.assetsPath('js/[id].[chunkhash].js')
    },
    //从输出的 bundle 中排除依赖
    //https://webpack.docschina.org/configuration/externals#root
    externals: {
        // 'vue': 'Vue',
        // 'vue-router': 'VueRouter',
        // 'vuex': 'Vuex',
        // 'axios': 'axios',
        // 'v-region': 'vRegion',
        // 'element-ui': 'ElementUI'
    },
    plugins: [
        // 分析bundle
        new BundleAnalyzerPlugin(),

        //vue-loader 打包*.vue文件
        new VueLoaderPlugin(),

        //清理 dist 文件夹
        //https://www.npmjs.com/package/clean-webpack-plugin
        new CleanWebpackPlugin(),

        //HtmlWebpackPlugin 简化了 HTML 文件的创建,以便为你的 webpack 包提供服务。
        //https://webpack.docschina.org/plugins/html-webpack-plugin/#installation
        //https://github.com/jantimon/html-webpack-plugin
        new HtmlWebpackPlugin({
            title: '实验室管家v2',
            filename: 'index.html',
            favicon: 'public/favicon.ico',
            template: 'public/index.html'
        }),

        //压缩css
        //https://v4.webpack.docschina.org/plugins/mini-css-extract-plugin/
        new MiniCssExtractPlugin({
            filename: utils.assetsPath('css/[name].[contenthash].css'),
            chunkFilename: utils.assetsPath('css/[id].[contenthash].css'),
        })


    ],
    optimization: {
        minimizer: [
            new TerserJSPlugin({}),
            new OptimizeCSSAssetsPlugin({}),
            //https://v4.webpack.docschina.org/plugins/uglifyjs-webpack-plugin/#getting-started
            new UglifyJsPlugin({
                cache: true,
                parallel: true,
                sourceMap: false,
                uglifyOptions: {
                    output: {
                        comments: false,
                    },
                },
            })
        ],
        //打包vendor
        //https://v4.webpack.docschina.org/plugins/split-chunks-plugin/
        splitChunks: {
            chunks: 'all',
            minChunks: 1,
            cacheGroups: {
                //Vue+Vuex+VueRouter+Axios+qs+cors-js(main.js里面的东西)
                libs: {
                    name: 'chunk-libs',
                    test: /[\\/]node_modules[\\/](vue|vuex|vue-router|axios|qs|cors-js)[\\/]/,
                    priority: 10,
                },
                //element-ui太大单独导出
                elementUI: {
                    name: 'chunk-elementUI', // split elementUI into a single package
                    priority: 15, // the weight needs to be larger than libs and app or it will be packaged into libs or app
                    test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
                },
                // //jExcel太大单独导出
                // jExcel: {
                //     name: 'chunk-jExcel', // split elementUI into a single package
                //     priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
                //     //test: /[\\/]node_modules[\\/]_?jspreadsheet-ce(.*)/, // in order to adapt to cnpm
                //     test: /[\\/]node_modules[\\/](jspreadsheet-ce|jsuites)[\\/]/,
                //     chunks: 'all',
                // },
                // //echarts太大单独导出
                // echarts: {
                //     name: 'chunk-echarts', // split elementUI into a single package
                //     priority: 30, // the weight needs to be larger than libs and app or it will be packaged into libs or app
                //     test: /[\\/]node_modules[\\/]_?echarts(.*)/ // in order to adapt to cnpm
                // },
                //v-region太大单独导出
                vRegion: {
                    name: 'chunk-vRegion', // split elementUI into a single package
                    priority: 35, // the weight needs to be larger than libs and app or it will be packaged into libs or app
                    test: /[\\/]node_modules[\\/]_?v-region(.*)/ // in order to adapt to cnpm
                },
            },
        }
    },
}))


module.exports = webpackConfig
posted @ 2022-05-09 08:32  烧刘病  阅读(80)  评论(0编辑  收藏  举报
回到页首