Webpack发布策略(生产模式)

新建webpack.pub.config.js  发布配置文件
在package.json中新增一个节点pub
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack-dev-server --open --port 3000 --contentBase src --hot",
    "pub":"webpack --config webpack.pub.config.js"
  }
每次要重新生成dist  
需要安装一个插件:cnpm install clean-webpack-plugin -D
导入每次删除文件夹的插件

const { CleanWebpackPlugin } = require("clean-webpack-plugin");
 
plugins: [
    new CleanWebpackPlugin()
]
分离第三方包,bundle.js中只保存自己的代码,其他的分离出去
参考这个链接鼓秋一下:不用下载插件啦。
https://github.com/webpack/webpack/tree/master/examples/common-chunk-and-vendor-chunk
安装JS代码压缩插件:   (貌似生产环境自动压缩了JS,不需要我们搞了,暂时不安)
cnpm install uglifyjs-webpack-plugin -D
const UglifyJsPlugin = require('uglifyjs-webpack-plugin');
...
optimization: { //与entry同级
    minimizer: [
      new UglifyJsPlugin({
        uglifyOptions: {
          compress: true,
          mangle: true,
          output: {
            comments: false,
          },
        },
        sourceMap: false,
      })
    ]   
},
抽离样式CSS:
cnpm install mini-css-extract-plugin -D
const MiniCssExtractPlugin = require("mini-css-extract-plugin");  
//这个插件应该只用在 production 配置中,并且在loaders链中不使用 style-loader

{test:/\.css$/,use:[{
    loader: MiniCssExtractPlugin.loader,
    options: {
        // 这里可以指定一个 publicPath
        // 默认使用 webpackOptions.output中的publicPath
        publicPath: './dist'
    }
},'css-loader']}, //配置处理.css文件的第三方loader规则

new MiniCssExtractPlugin({
    filename: "./css/[name].[hash:8].css"
}),      
cnpm install optimize-css-assets-webpack-plugin -D
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');      //压缩css插件

new OptimizeCssAssetsPlugin(),      //压缩css文件

下面是最终完整版的production环境配置、以及目录结构:

webpack.pub.config.js

const path = require('path');
const webpack = require('webpack');
const htmlWebpackPlugin = require('html-webpack-plugin');
const { CleanWebpackPlugin } = require("clean-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");        //提取成单个css文件
const OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');      //压缩css插件
// const UglifyJsPlugin = require('uglifyjs-webpack-plugin'); //压缩JS代码  貌似生产环境自动压缩


module.exports = {
    mode: 'production',
    entry: {
        bundle:path.join(__dirname,'./src/js/main.js'),  // 入口文件
        // pageB: "./pageB",  //多入口
		// pageC: "./pageC"
    },
	optimization: {
		chunkIds: "named",
		splitChunks: {
			cacheGroups: {
				commons: {
					chunks: "initial",
					minChunks: 2,
					maxInitialRequests: 5, 
					minSize: 0 
				},
				vendor: {
					test: /node_modules/,        //如果是node_modules中的第三方库那么打包成vendor
					chunks: "initial",
					name: "vendors",
					priority: 10,
					enforce: true
				}
			}
        }
	},
    output:{
        path:path.join(__dirname,'./dist'),   //输出文件目录
        filename: "./js/[name].js"
    },
    plugins:[new htmlWebpackPlugin({
        // favicon: path.join(__dirname,'./src/img/favicon.ico'), //图标
        template:path.join(__dirname,'./src/index.html'),  //指定模板页面,将来会根据指定页面的路径去生成内存中的页面
        filename:'index.html', //指定生成的页面的名称
        minify: {                       //压缩
            removeComments: true,       //移除HTML中的注释
            collapseWhitespace:true,        //删除空白符与换行符
            removeAttributeQuotes: true        //去除属性引用
        }
    }),       
    // new HtmlWebpackPlugin(//打包第二个页面
    //     {
    //         template: './app/src/page/index2.html',
    //         filename:'./page/index2.html'
    //     }),
    new MiniCssExtractPlugin({
        filename: "./css/[name].[hash:8].css"
    }),
    new OptimizeCssAssetsPlugin(),      //压缩css文件
    new CleanWebpackPlugin(),
    new webpack.optimize.RuntimeChunkPlugin({name:"manifest"}),
    ],
    module:{
        rules:[
            {test: /\.js|jsx$/, use:{loader:'babel-loader',options:{presets: ['@babel/preset-env','@babel/preset-react']}},exclude: /node_modules/},
            {test:/\.css$/,use:[{
                loader: MiniCssExtractPlugin.loader,
                options: {
                  // 这里可以指定一个 publicPath
                  // 默认使用 webpackOptions.output中的publicPath
                  publicPath: './../'    //为了找到images目录 
                }
            },'css-loader']}, //配置处理.css文件的第三方loader规则
            {test:/\.less$/,use:['style-loader','css-loader','less-loader']},//配置.less文件的第三方loader
            {test:/\.scss$/,use:['style-loader','css-loader','sass-loader']},
            // {test:/\.(jpg|png|gif|bmp|jpeg)$/,use:'url-loader?limit=100&name=[hash:8]-[name].[ext]'},
            {test: /\.(png|jpe?g|gif|svg|bmp)(\?.*)?$/,loader: 'url-loader',options: {limit: 5000,name:'./images/[name].[hash:8].[ext]',}} , //处理图片路径的loader,如果引用的图片小于xxbytes则会转为base64
            {test:/\.(ttf|eot|svg|woff|woff2)$/,use:'url-loader'},  //处理字体文件
        ]
    }//用于配置所有第三方模块加载器
  }

package.json

{
  "name": "WWW",
  "version": "1.0.0",
  "description": "",
  "main": "webpack.config.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "dev": "webpack-dev-server --open --port 3000 --hot",
    "pub": "webpack --config webpack.pub.config.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/core": "^7.7.2",
    "@babel/plugin-transform-runtime": "^7.6.2",
    "@babel/preset-env": "^7.7.1",
    "@babel/preset-react": "^7.7.0",
    "@babel/preset-stage-0": "^7.0.0",
    "babel-loader": "^8.0.6",
    "babel-preset-mobx": "^2.0.0",
    "clean-webpack-plugin": "^3.0.0",
    "css-loader": "^3.2.0",
    "extract-text-webpack-plugin": "^3.0.2",
    "file-loader": "^4.2.0",
    "html-webpack-plugin": "^3.2.0",
    "less": "^3.10.3",
    "less-loader": "^5.0.0",
    "mini-css-extract-plugin": "^0.8.0",
    "optimize-css-assets-webpack-plugin": "^5.0.3",
    "sass": "^1.23.7",
    "sass-loader": "^8.0.0",
    "style-loader": "^1.0.0",
    "terser-webpack-plugin": "^2.2.1",
    "uglifyjs-webpack-plugin": "^2.2.0",
    "url-loader": "^2.2.0",
    "webpack": "^4.41.2",
    "webpack-cli": "^3.3.10",
    "webpack-dev-server": "^3.9.0"
  },
  "dependencies": {
    "@babel/core": "^7.7.2",
    "@babel/plugin-transform-runtime": "^7.6.2",
    "@babel/preset-env": "^7.7.1",
    "@babel/preset-react": "^7.7.0",
    "@babel/preset-stage-0": "^7.0.0",
    "babel-loader": "^8.0.6",
    "babel-preset-mobx": "^2.0.0",
    "clean-webpack-plugin": "^3.0.0",
    "css-loader": "^3.2.0",
    "file-loader": "^4.2.0",
    "html-webpack-plugin": "^3.2.0",
    "less": "^3.10.3",
    "less-loader": "^5.0.0",
    "mini-css-extract-plugin": "^0.8.0",
    "optimize-css-assets-webpack-plugin": "^5.0.3",
    "sass": "^1.23.7",
    "sass-loader": "^8.0.0",
    "style-loader": "^1.0.0",
    "terser-webpack-plugin": "^2.2.1",
    "uglifyjs-webpack-plugin": "^2.2.0",
    "url-loader": "^2.2.0",
    "webpack": "^4.41.2",
    "webpack-cli": "^3.3.10",
    "webpack-dev-server": "^3.9.0"
  }
}

babelrc.json

{
    "presets":["@babel/preset-env","@babel/preset-react","@babel/preset-stage-0","mobx"],
    "plugins":["@babel/plugin-transform-runtime"]
}

下面是我写的纯净版框架链接:见github

发表评论

电子邮件地址不会被公开。 必填项已用*标注