什么是webpack
webpack是一個module bundler(模塊打包工具),所謂的模塊就是在平時的前端開發中,用到一些靜態資源,如JavaScript、CSS、圖片等文件,webpack就將這些靜態資源文件稱之為模塊
webpack支持AMD和CommonJS,以及其他的一些模塊系統,并且兼容多種JS書寫規范,可以處理模塊間的以來關系,所以具有更強大的JS模塊化的功能,它能對靜態資源進行統一的管理以及打包發布,在官網中用這張圖片介紹:

它在很多地方都能替代Grunt和Gulp,因為它能夠編譯打包CSS,做CSS預處理,對JS的方言進行編譯,打包圖片,代碼壓縮等等。所以在我接觸了webpack之后,就不太想用gulp了
為什么使用webpack
總結如下:
webpack主要是用于vue和React較多,其實它就非常像Browserify,但是將應用打包為多個文件。如果單頁面應用有多個頁面,那么用戶只從下載對應頁面的代碼. 當他么訪問到另一個頁面, 他們不需要重新下載通用的代碼。
基于本人項目使用
vue webpack的配置文件的基本目錄結構如下:
config├── dev.env.js //dev環境變量配置├── index.js // dev和prod環境的一些基本配置└── prod.env.js // prod環境變量配置build├── build.js // npm run build所執行的腳本├── check-versions.js // 檢查npm和node的版本├── logo.png├── utils.js // 一些工具方法,主要用于生成cssLoader和styleLoader配置├── vue-loader.conf.js // vueloader的配置信息├── webpack.base.conf.js // dev和prod的公共配置├── webpack.dev.conf.js // dev環境的配置└── webpack.prod.conf.js // prod環境的配置
Config文件夾下文件詳解
dev.env.js
config內的文件其實是服務于build的,大部分是定義一個變量export出去
use strict //[采用嚴格模式]/*** [webpack-merge提供了一個合并函數,它將數組和合并對象創建一個新對象] */const merge = require('webpack-merge')const prodEnv = require('./prod.env')module.exports = merge(prodEnv, { NODE_ENV: '"development"'})prod.env.js
當開發時調取dev.env.js的開發環境配置,發布時調用prod.env.js的生產環境配置
use strictmodule.exports = {NODE_ENV: '"production"'}index.js
const path = require('path')module.exports = { /** * [開發環境配置] */dev: { assetsSubDirectory: 'static', // [子目錄,一般存放css,js,image等文件]assetsPublicPath: '/', // [根目錄]/*** [配置服務代理] */ proxyTable: { '/hcm': { target: 'https://127.0.0.1:8448', changeOrigin: true, secure: false }, headers: { "Access-Control-Allow-Origin": "*", "Access-Control-Allow-Methods": "GET, POST, PUT, DELETE, PATCH, OPTIONS", "Access-Control-Allow-Headers": "X-Requested-With, content-type, Authorization" } }, host: '127.0.0.1', // [瀏覽器訪問地址] port: 8083, // [端口號設置,端口號占用出現問題可在此處修改] autoOpenBrowser: true, // [是否在編譯(輸入命令行npm run dev)后打開http://127.0.0.1:8083/頁面] errorOverlay: true, // [瀏覽器錯誤提示] notifyOnErrors: true, // [跨平臺錯誤提示] poll:false, // [使用文件系統(file system)獲取文件改動的通知devServer.watchOptions] useEslint: true, // [是否啟用代碼規范檢查] showEslintErrorsInOverlay: false, // [是否展示eslint的錯誤提示] devtool: 'eval-source-map', // [增加調試,該屬性為原始源代碼] cacheBusting: true, // [使緩存失效] cssSourceMap: false // [代碼壓縮后進行調bug定位將非常困難,于是引入sourcemap記錄壓縮前后的位置信息記錄,當產生錯誤時直接定位到未壓縮前的位置,將大大的方便我們調試] },/*** [生產環境配置] */ build: { /*** [index、login、license、forbidden、notfound、Internal.licenses編譯后生成的位置和名字,根據需要改變后綴] */ index: path.resolve(__dirname, '../../hcm-modules/hcm-web/src/main/resources/META-INF/resources/index.html'), login: path.resolve(__dirname, '../../hcm-modules/hcm-web/src/main/resources/META-INF/resources/login.html'), license: path.resolve(__dirname, '../../hcm-modules/hcm-web/src/main/resources/META-INF/resources/license.html'), forbidden: path.resolve(__dirname, '../../hcm-modules/hcm-web/src/main/resources/META-INF/resources/error/403.html'), notfound: path.resolve(__dirname, '../../hcm-modules/hcm-web/src/main/resources/META-INF/resources/error/404.html'), internal: path.resolve(__dirname, '../../hcm-modules/hcm-web/src/main/resources/META-INF/resources/error/500.html'), licenses: path.resolve(__dirname, '../../hcm-modules/hcm-web/src/main/resources/META-INF/resources/docs/licenses.html'),/*** [編譯后存放生成環境代碼的位置] */ assetsRoot: path.resolve(__dirname, '../../hcm-modules/hcm-web/src/main/resources/META-INF/resources'), assetsSubDirectory: 'static', //js、css、images存放文件夾名 assetsPublicPath: './', //發布的根目錄,通常本地打包dist后打開文件會報錯,此處修改為./。如果是上線的文件,可根據文件存放位置進行更改路徑 productionSourceMap: true, devtool: '#source-map', productionGzip: false, //unit的gzip命令用來壓縮文件,gzip模式下需要壓縮的文件的擴展名有js和css productionGzipExtensions: ['js', 'css'], bundleAnalyzerReport: process.env.npm_config_report //打包分析 }}build文件夾下文件詳解
build.js
該文件作用,即構建生產版本。package.json中的scripts的build就是node build/build.js,輸入命令行npm run build對該文件進行編譯生成生產環境的代碼。
require('./check-versions')() //check-versions:調用檢查版本的文件。加()代表直接調用該函數process.env.NODE_ENV = 'production' //設置當前是生產環境/***下面定義常量引入插件*/const ora = require('ora') //加載動畫const rm = require('rimraf') //刪除文件const path = require('path')const chalk = require('chalk') //對文案輸出的一個彩色設置const webpack = require('webpack')const config = require('../config') //默認讀取下面的index.js文件const webpackConfig = require('./webpack.prod.conf')const spinner = ora('building for production...') //調用start的方法實現加載動畫,優化用戶體驗spinner.start()//先刪除dist文件再生成新文件,因為有時候會使用hash來命名,刪除整個文件可避免冗余rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => { if (err) throw err webpack(webpackConfig, (err, stats) => { spinner.stop() if (err) throw err process.stdout.write(stats.toString({ colors: true, modules: false, children: false, chunks: false, chunkModules: false }) + '/n/n') if (stats.hasErrors()) { console.log(chalk.red(' Build failed with errors./n')) process.exit(1) } console.log(chalk.cyan(' Build complete./n')) console.log(chalk.yellow( ' Tip: built files are meant to be served over an HTTP server./n' + ' Opening index.html over file:// won/'t work./n' )) })})check-versions.js
該文件用于檢測node和npm的版本,實現版本依賴
const chalk = require('chalk') const semver = require('semver') //對版本進行檢查const packageConfig = require('../package.json')const shell = require('shelljs')function exec (cmd) { //返回通過child_process模塊的新建子進程,執行 Unix 系統命令后轉成沒有空格的字符串 return require('child_process').execSync(cmd).toString().trim()}const versionRequirements = [ { name: 'node', currentVersion: semver.clean(process.version), //使用semver格式化版本 versionRequirement: packageConfig.engines.node //獲取package.json中設置的node版本 }]if (shell.which('npm')) { versionRequirements.push({ name: 'npm', currentVersion: exec('npm --version'), // 自動調用npm --version命令,并且把參數返回給exec函數,從而獲取純凈的版本號 versionRequirement: packageConfig.engines.npm })}module.exports = function () { const warnings = [] for (let i = 0; i < versionRequirements.length; i++) { const mod = versionRequirements[i] if (!semver.satisfies(mod.currentVersion, mod.versionRequirement)) { //上面這個判斷就是如果版本號不符合package.json文件中指定的版本號,就執行下面錯誤提示的代碼warnings.push(mod.name + ': ' + chalk.red(mod.currentVersion) + ' should be ' + chalk.green(mod.versionRequirement) ) } } if (warnings.length) { console.log('') console.log(chalk.yellow('To use this template, you must update following to modules:')) console.log() for (let i = 0; i < warnings.length; i++) { const warning = warnings[i] console.log(' ' + warning) } console.log() process.exit(1) }}utils.js
utils是工具的意思,是一個用來處理css的文件。
const path = require('path')const config = require('../config')const ExtractTextPlugin = require('extract-text-webpack-plugin')const packageConfig = require('../package.json')exports.assetsPath = function (_path) { const assetsSubDirectory = process.env.NODE_ENV === 'production' ? config.build.assetsSubDirectory : config.dev.assetsSubDirectory return path.posix.join(assetsSubDirectory, _path)}exports.cssLoaders = function (options) { options = options || {}//使用了css-loader和postcssLoader,通過options.usePostCSS屬性來判斷是否使用postcssLoader中壓縮等方法 const cssLoader = { loader: 'css-loader', options: { sourceMap: options.sourceMap } } const postcssLoader = { loader: 'postcss-loader', options: { sourceMap: options.sourceMap } } // generate loader string to be used with extract text plugin function generateLoaders (loader, loaderOptions) { const loaders = options.usePostCSS ? [cssLoader, postcssLoader] : [cssLoader] if (loader) { loaders.push({ loader: loader + '-loader', //Object.assign是es6語法的淺復制,后兩者合并后復制完成賦值 options: Object.assign({}, loaderOptions, { sourceMap: options.sourceMap }) }) } // Extract CSS when that option is specified // (which is the case during production build)if (options.extract) {//ExtractTextPlugin可提取出文本,代表首先使用上面處理的loaders,當未能正確引入時使用vue-style-loader return ExtractTextPlugin.extract({ use: loaders, fallback: 'vue-style-loader', publicPath: '../../' })} else {//返回vue-style-loader連接loaders的最終值 return ['vue-style-loader'].concat(loaders) } } // https://vue-loader.vuejs.org/en/configurations/extract-css.html return { css: generateLoaders(),//需要css-loader 和 vue-style-loader postcss: generateLoaders(),//需要css-loader和postcssLoader 和 vue-style-loader less: generateLoaders('less'), //需要less-loader 和 vue-style-loader sass: generateLoaders('sass', { indentedSyntax: true }), //需要sass-loader 和 vue-style-loader scss: generateLoaders('sass'), //需要sass-loader 和 vue-style-loader stylus: generateLoaders('stylus'), //需要stylus-loader 和 vue-style-loader styl: generateLoaders('stylus') //需要stylus-loader 和 vue-style-loader }}// Generate loaders for standalone style files (outside of .vue)exports.styleLoaders = function (options) { const output = [] const loaders = exports.cssLoaders(options)//將各種css,less,sass等綜合在一起得出結果輸出output for (const extension in loaders) { const loader = loaders[extension] output.push({ test: new RegExp('//.' + extension + '$'), use: loader }) } return output}exports.createNotifierCallback = () => {//發送跨平臺通知系統 const notifier = require('node-notifier') return (severity, errors) => {if (severity !== 'error') return//當報錯時輸出錯誤信息的標題,錯誤信息詳情,副標題以及圖標 const error = errors[0] const filename = error.file && error.file.split('!').pop() notifier.notify({ title: packageConfig.name, message: severity + ': ' + error.name, subtitle: filename || '', icon: path.join(__dirname, 'logo.png') }) }}vue-loader.conf.js
該文件的主要作用就是處理.vue文件,解析這個文件中的每個語言塊(template、script、style),轉換成js可用的js模塊。
const utils = require('./utils')const config = require('../config')const isProduction = process.env.NODE_ENV === 'production'const sourceMapEnabled = isProduction ? config.build.productionSourceMap : config.dev.cssSourceMap//處理項目中的css文件,生產環境和測試環境默認是打開sourceMap,而extract中的提取樣式到單獨文件只有在生產環境中才需要module.exports = { loaders: utils.cssLoaders({ sourceMap: sourceMapEnabled, extract: isProduction }), cssSourceMap: sourceMapEnabled, cacheBusting: config.dev.cacheBusting,// 在模版編譯過程中,編譯器可以將某些屬性,如 src 路徑,轉換為require調用,以便目標資源可以由 webpack 處理 transformToRequire: { video: ['src', 'poster'], source: 'src', img: 'src', image: 'xlink:href' }}webpack.base.conf.js
webpack.base.conf.js是開發和生產共同使用提出來的基礎配置文件,主要實現配制入口,配置輸出環境,配置模塊resolve和插件等
const path = require('path')const utils = require('./utils')/*** [引入index.js文件路徑] */const config = require('../config')const vueLoaderConfig = require('./vue-loader.conf')/** * [獲取文件路徑] * @param dir [文件名稱] *_dirname為當前模塊文件所在目錄的絕對路徑* *@return 文件絕對路徑*/function resolve (dir) { return path.join(__dirname, '..', dir)}const createLintingRule = () => ({ test: //.(js|vue)$/, loader: 'eslint-loader', enforce: 'pre', include: [resolve('src'), resolve('test')], options: { formatter: require('eslint-friendly-formatter'), emitWarning: !config.dev.showEslintErrorsInOverlay }})module.exports = { context: path.resolve(__dirname, '../'), /** * [入口文件配置] */ entry: {/** * [入口文件路徑, babel-polyfill是對es6語法的支持] */ app: ['babel-polyfill', './src/main.js'], login: ['babel-polyfill', './src/loginMain.js'], license: ['babel-polyfill', './src/licenseMain.js'] },/** * [文件導出配置]*/ output: { path: config.build.assetsRoot, filename: '[name].js', publicPath: process.env.NODE_ENV === 'production' ? config.build.assetsPublicPath : config.dev.assetsPublicPath //公共存放路徑 }, resolve: { /** * [extensions: 配置文件的擴展名,當在important文件時,不用需要添加擴展名] */extensions: ['.js', '.vue', '.json'],/** * [alias 給路徑定義別名]*/ alias: { 'vue$': 'vue/dist/vue.esm.js', '@': resolve('src') } },/***使用插件配置相應文件的處理方法*/ module: {rules: [ ...(config.dev.useEslint ? [createLintingRule()] : []),/** * [使用vue-loader將vue文件轉化成js的模塊]*/ { test: //.vue$/, loader: 'vue-loader', options: vueLoaderConfig },/** * [通過babel-loader將js進行編譯成es5/es6 文件]*/ { test: //.js$/, loader: 'babel-loader', include: [resolve('src'), resolve('test')] },/** * [圖片、音像、字體都使用url-loader進行處理,超過10000會編譯成base64]*/ { 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]') } },/** * [canvas 解析]*/ { test: path.resolve(`${resolve('src')}/lib/jtopo.js`), loader: ['exports-loader?window.JTopo', 'script-loader'] } ] },//以下選項是Node.js全局變量或模塊,這里主要是防止webpack注入一些Node.js的東西到vue中 node: { setImmediate: false, dgram: 'empty', fs: 'empty', net: 'empty', tls: 'empty', child_process: 'empty' }}webpack.dev.conf.js
const path = require('path')const utils = require('./utils')const webpack = require('webpack')const config = require('../config')//通過webpack-merge實現webpack.dev.conf.js對wepack.base.config.js的繼承const merge = require('webpack-merge')const baseWebpackConfig = require('./webpack.base.conf')const HtmlWebpackPlugin = require('html-webpack-plugin')//美化webpack的錯誤信息和日志的插件const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')// 查看空閑端口位置,默認情況下搜索8000這個端口const portfinder = require('portfinder')// processs為node的一個全局對象獲取當前程序的環境變量,即hostconst HOST = process.env.HOSTconst PORT = process.env.PORT && Number(process.env.PORT)function resolveApp(relativePath) { return path.resolve(relativePath);}const devWebpackConfig = merge(baseWebpackConfig, { module: {//規則是工具utils中處理出來的styleLoaders,生成了css,less,postcss等規則 rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true }) },// 增強調試 devtool: config.dev.devtool,// 此處的配置都是在config的index.js中設定好了 devServer: {//控制臺顯示的選項有none, error, warning 或者 infoclientLogLevel: 'warning',//使用 HTML5 History APIhistoryApiFallback: true,hot: true, //熱加載compress: true, //壓縮 host: HOST || config.dev.host,port: PORT || config.dev.port,open: config.dev.autoOpenBrowser, //調試時自動打開瀏覽器 overlay: config.dev.errorOverlay ? { warnings: false, errors: true } : false, publicPath: config.dev.assetsPublicPath,proxy: config.dev.proxyTable,//接口代理quiet: true, //控制臺是否禁止打印警告和錯誤,若用FriendlyErrorsPlugin 此處為 true watchOptions: { poll: config.dev.poll, // 文件系統檢測改動 } }, plugins: [ new webpack.DefinePlugin({ 'process.env': require('../config/dev.env') }),new webpack.HotModuleReplacementPlugin(),//模塊熱替換插件,修改模塊時不需要刷新頁面new webpack.NamedModulesPlugin(), // 顯示文件的正確名字new webpack.NoEmitOnErrorsPlugin(), //當webpack編譯錯誤的時候,來中端打包進程,防止錯誤代碼打包到文件中// https://github.com/ampedandwired/html-webpack-plugin// 該插件可自動生成一個 html5 文件或使用模板文件將編譯好的代碼注入進去 new HtmlWebpackPlugin({ filename: 'index.html', template: 'index.html', inject: true, chunks: ['app'] }), new HtmlWebpackPlugin({ filename: 'login.html', template: 'login.html', inject: true, chunks: ['login'] }), new HtmlWebpackPlugin({ filename: 'license.html', template: 'license.html', inject: true, chunks: ['license'] }), new HtmlWebpackPlugin({ filename: 'licenses.html', template: 'licenses.html', inject: true, chunks: [] }), new HtmlWebpackPlugin({ filename: '404.html', template: path.resolve(__dirname, '../errors/404.html'), favicon: resolveApp('favicon.ico'), inject: true, chunks: [] }), new HtmlWebpackPlugin({ filename: '403.html', template: path.resolve(__dirname, '../errors/403.html'), favicon: resolveApp('favicon.ico'), inject: true, chunks: [] }), new HtmlWebpackPlugin({ filename: '500.html', template: path.resolve(__dirname, '../errors/500.html'), favicon: resolveApp('favicon.ico'), inject: true, chunks: [] }) ]})module.exports = new Promise((resolve, reject) => { portfinder.basePort = process.env.PORT || config.dev.port//查找端口號 portfinder.getPort((err, port) => { if (err) { reject(err)} else {//端口被占用時就重新設置evn和devServer的端口 process.env.PORT = port // add port to devServer config devWebpackConfig.devServer.port = port//友好地輸出信息 devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({ compilationSuccessInfo: { messages: [`Your application is running here: http://${devWebpackConfig.devServer.host}:${port}`], }, onErrors: config.dev.notifyOnErrors ? utils.createNotifierCallback() : undefined })) resolve(devWebpackConfig) } })})webpack.prod.conf.js
const path = require('path')const utils = require('./utils')const webpack = require('webpack')const config = require('../config')const merge = require('webpack-merge')const baseWebpackConfig = require('./webpack.base.conf')const CopyWebpackPlugin = require('copy-webpack-plugin')const HtmlWebpackPlugin = require('html-webpack-plugin')const ExtractTextPlugin = require('extract-text-webpack-plugin')const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin')const UglifyJsPlugin = require('uglifyjs-webpack-plugin')const env = require('../config/prod.env')function resolveApp(relativePath) { return path.resolve(relativePath);}const webpackConfig = merge(baseWebpackConfig, { module: { rules: utils.styleLoaders({ sourceMap: config.build.productionSourceMap,//開啟調試的模式。默認為true extract: true, usePostCSS: true }) }, devtool: config.build.productionSourceMap ? config.build.devtool : false, output: { path: config.build.assetsRoot, filename: utils.assetsPath('js/[name].[chunkhash].js'), chunkFilename: utils.assetsPath('js/[id].[chunkhash].js') }, plugins: [ // http://vuejs.github.io/vue-loader/en/workflow/production.html new webpack.DefinePlugin({ 'process.env': env }), new UglifyJsPlugin({ uglifyOptions: { compress: { warnings: false //警告:true保留警告,false不保留 } }, sourceMap: config.build.productionSourceMap, parallel: true }),// extract css into its own file//抽取文本。比如打包之后的index頁面有style插入,就是這個插件抽取出來的,減少請求new ExtractTextPlugin({ filename: utils.assetsPath('css/[name].[contenthash].css'), allChunks: true,}),//優化css的插件 new OptimizeCSSPlugin({ cssProcessorOptions: config.build.productionSourceMap ? { safe: true, map: { inline: false } } : { safe: true } }), //html打包 new HtmlWebpackPlugin({ filename: config.build.index, template: 'index.html', inject: true,//壓縮 minify: { removeComments: true, //刪除注釋 collapseWhitespace: true, //刪除空格 removeAttributeQuotes: true //刪除屬性的引號 }, chunks: ['vendor', 'manifest', 'app'], // necessary to consistently work with multiple chunks via CommonsChunkPlugin chunksSortMode: 'dependency' }), new HtmlWebpackPlugin({ filename: config.build.login, template: 'login.html', inject: true, minify: { removeComments: true, collapseWhitespace: true, removeAttributeQuotes: true }, chunks: ['vendor', 'manifest', 'login'], // necessary to consistently work with multiple chunks via CommonsChunkPlugin chunksSortMode: 'dependency' }), new HtmlWebpackPlugin({ filename: config.build.license, template: 'license.html', inject: true, minify: { removeComments: true, collapseWhitespace: true, removeAttributeQuotes: true }, chunks: ['vendor', 'manifest', 'license'], // necessary to consistently work with multiple chunks via CommonsChunkPlugin chunksSortMode: 'dependency' }), new HtmlWebpackPlugin({ filename: config.build.notfound, template: path.resolve(__dirname, '../errors/404.html'), inject: true, favicon: resolveApp('favicon.ico'), minify: { removeComments: true, collapseWhitespace: true, removeAttributeQuotes: true }, chunks: [], // necessary to consistently work with multiple chunks via CommonsChunkPlugin chunksSortMode: 'dependency' }), new HtmlWebpackPlugin({ filename: config.build.forbidden, template: path.resolve(__dirname, '../errors/403.html'), inject: true, favicon: resolveApp('favicon.ico'), minify: { removeComments: true, collapseWhitespace: true, removeAttributeQuotes: true }, chunks: [], // necessary to consistently work with multiple chunks via CommonsChunkPlugin chunksSortMode: 'dependency' }), new HtmlWebpackPlugin({ filename: config.build.internal, template: path.resolve(__dirname, '../errors/500.html'), inject: true, favicon: resolveApp('favicon.ico'), minify: { removeComments: true, collapseWhitespace: true, removeAttributeQuotes: true }, chunks: [], // necessary to consistently work with multiple chunks via CommonsChunkPlugin chunksSortMode: 'dependency' }), new HtmlWebpackPlugin({ filename: config.build.licenses, template: 'licenses.html', inject: true, minify: { removeComments: true, collapseWhitespace: true, removeAttributeQuotes: true }, chunks: [], // necessary to consistently work with multiple chunks via CommonsChunkPlugin chunksSortMode: 'dependency' }), // keep module.id stable when vender modules does not change new webpack.HashedModuleIdsPlugin(), // enable scope hoistingnew webpack.optimize.ModuleConcatenationPlugin(),//抽取公共的模塊, 提升你的代碼在瀏覽器中的執行速度。 new webpack.optimize.CommonsChunkPlugin({ name: 'vendor', minChunks (module) { // any required modules inside node_modules are extracted to vendor return ( module.resource && //.js$/.test(module.resource) && module.resource.indexOf( path.join(__dirname, '../node_modules') ) === 0 ) } }), // extract webpack runtime and module manifest to its own file in order to // prevent vendor hash from being updated whenever app bundle is updated new webpack.optimize.CommonsChunkPlugin({ name: 'manifest', minChunks: Infinity}),// 預編譯所有模塊到一個閉包中, new webpack.optimize.CommonsChunkPlugin({ name: 'app', async: 'vendor-async', children: true, minChunks: 3 }),//復制,比如打包完之后需要把打包的文件復制到dist里面 new CopyWebpackPlugin([ { from: path.resolve(__dirname, '../static'), to: config.build.assetsSubDirectory, ignore: ['.*'] } ]) ]})if (config.build.productionGzip) { const CompressionWebpackPlugin = require('compression-webpack-plugin') webpackConfig.plugins.push( new CompressionWebpackPlugin({ asset: '[path].gz[query]', algorithm: 'gzip', test: new RegExp( '//.(' + config.build.productionGzipExtensions.join('|') + ')$' ), threshold: 10240, minRatio: 0.8 }) )}// 提供帶 Content-Encoding 編碼的壓縮版的資源if (config.build.bundleAnalyzerReport) { const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin webpackConfig.plugins.push(new BundleAnalyzerPlugin())}module.exports = webpackConfig以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答