What is a Webpack-chain? Modify the webPack configuration in a chained manner.
Some lists my common ways to modify webPack configurations using Webpack-chain. The entire file is:
//vue.config.js
module.exports={
chainWebpack:(webpackConfig)=>{
}
}
Copy the code
#1. Modify entry and output
chainWebpack: Config.entry ('main').add('./ SRC /main.js')// Add entry Config.entry ('routes').add('./ SRC /app-routes.js')// Add config.output.path ("dist").filename("[name].[chunkhash].js") .chunkFilename("chunks/[name].[chunkhash].js") .libraryTarget("umd") .library(); } config.output. AuxiliaryComment (auxiliaryComment).chunkFilename(chunkFilename) .chunkLoadTimeout(chunkLoadTimeout) .crossOriginLoading(crossOriginLoading) .devtoolFallbackModuleFilenameTemplate(devtoolFallbackModuleFilenameTemplate) .devtoolLineToLine(devtoolLineToLine) .devtoolModuleFilenameTemplate(devtoolModuleFilenameTemplate) .filename(filename) .hashFunction(hashFunction) .hashDigest(hashDigest) .hashDigestLength(hashDigestLength) .hashSalt(hashSalt) .hotUpdateChunkFilename(hotUpdateChunkFilename) .hotUpdateFunction(hotUpdateFunction) .hotUpdateMainFilename(hotUpdateMainFilename) .jsonpFunction(jsonpFunction) .library(library) .libraryExport(libraryExport) .libraryTarget(libraryTarget) .path(path) .pathinfo(pathinfo) .publicPath(publicPath) .sourceMapFilename(sourceMapFilename) .sourcePrefix(sourcePrefix) .strictModuleExceptionHandling(strictModuleExceptionHandling) .umdNamedDefine(umdNamedDefine)Copy the code
#2. Set the alias
const path = require('path'); function resolve (dir) { return path.join(__dirname, dir) } module.exports = { lintOnSave: true, chainWebpack: (config)=>{ config.resolve.alias .set('@$', resolve('src')) .set('assets',resolve('src/assets')) .set('components',resolve('src/components')) .set('layout',resolve('src/layout')) .set('base',resolve('src/base')) .set('static',resolve('src/static')) .delete('base') // delete the specified alias //.clear() will delete all aliases}}Copy the code
#3. Modify proxy
For the devServe configuration, see here
chainWebpack: config => { config.devServer.port(8888) .open(true) .proxy({'/dev': { target: 'http://123.57.153.106:8080/', changeOrigin: true, pathRewrite: {' ^ / dev ': Config.devserver.bonjour (Bonjour).clientLogLevel(clientLogLevel).color(color) .compress(compress) .contentBase(contentBase) .disableHostCheck(disableHostCheck) .filename(filename) .headers(headers) .historyApiFallback(historyApiFallback) .host(host) .hot(hot) .hotOnly(hotOnly) .https(https) .inline(inline) .info(info) .lazy(lazy) .noInfo(noInfo) .open(open) .openPage(openPage) .overlay(overlay) .pfx(pfx) .pfxPassphrase(pfxPassphrase) .port(port) .progress(progress) .proxy(proxy) .public(public) .publicPath(publicPath) .quiet(quiet) .setup(setup) .socket(socket) .staticOptions(staticOptions) .stats(stats) .stdin(stdin) .useLocalIp(useLocalIp) .watchContentBase(watchContentBase) .watchOptions(watchOptions)Copy the code
#4. Add plug-ins and modify plug-in parameters
For plug-in configuration, see here
Add the plug-in
// Add API config.plugin (name).use(WebpackPlugin, Args) // An example const fileManager = require("filemanager-webpack-plugin"); . Plugin ("zip").use(fileManager, [{onEnd: {archive: [{source: "dist", destination: zipName } ] } } ]);Copy the code
Modifying plug-in parameters
// You can use the tap mode, Plugin.tap (args => newArgs) // An example config.plugin ('env') // Modify the plugin.tap (args => [...args, 'SECRET_KEY']);Copy the code
#5. Modify plug-in initialization and remove plug-in
Modify plug-in initialization
config .plugin(name) .init((Plugin, args) => new Plugin(... args));Copy the code
Remove the plug-in
ChainWebpack: config => {config.plugins.delete('prefetch') // Remove the preload plugin config.plugins.delete('preload'); }Copy the code
#6. Call before/after xx plug-in
Sometimes the XX plug-in needs to be called before the AA plug-in.
Config.plugin (name).before(otherName) // An example: Config. Plugin ('html-template').use(HtmlWebpackTemplate).end() .plugin('script-ext') .use(ScriptExtWebpackPlugin) .before('html-template');Copy the code
Sometimes the XX plug-in needs to be called after the AA plug-in.
Config.plugin (name).after(otherName) // An example html-template calls config.plugin ('html-template') after script-ext .after('script-ext') .use(HtmlWebpackTemplate) .end() .plugin('script-ext') .use(ScriptExtWebpackPlugin);Copy the code
#7. Performance
For configuration, see Webpack Parameter: Performance
The config. Performance. Hints (hints) / / false | | "error", "warning". Turn on/off prompts. MaxEntrypointSize (maxEntrypointSize)// The entry starting point indicates that the initial load time period for all resources is to be fully utilized for the specified entry. This option controls when WebPack generates performance hints based on the maximum size of the entry starting point. The default is: 250000. MaxAssetSize (maxAssetSize)// Asset is any file generated from WebPack. This option controls when WebPack generates performance hints based on the volume of a single resource. The default is: 250000. AssetFilter (assetFilter)// This property allows WebPack to control the files used to calculate performance hintsCopy the code
#8. Code segmentation and performance optimizations
- Introduction to Optimizations configuration
- Code split configuration
- Introduction to splitChunk in Chinese
config.optimization .concatenateModules(concatenateModules) .flagIncludedChunks(flagIncludedChunks) MergeDuplicateChunks (mergeDuplicateChunks). Minimize (minimize) / / a Boolean, NamedChunks (namedChunks).namedModules(namedModules).nodeEnv(nodeEnv).noemitonErrors (noEmitOnErrors) .occurrenceOrder(occurrenceOrder) .portableRecords(portableRecords) .providedExports(providedExports) .removeAvailableModules(removeAvailableModules) .removeEmptyChunks(removeEmptyChunks) .runtimeChunk(runtimeChunk) .sideEffects(sideEffects).splitchunks (splitChunks)// Object: Code splitting By default, WebPack V4 + provides a new generic block strategy for dynamically imported modules out of the box. . UsedExports (usedExports) / / config. The example optimization. SplitChunks ({chunks: "Async", / / must choose three: "initial" | "all" (recommended) | "async" (the default is async) minSize: 30000, / / minimal size, 30000 minChunks: MaxAsyncRequests: quests (maxInitialRequests) AutomaticNameDelimiter: '~',// pack separator name: Function cacheGroups:{// start setting chunks priority: 0, // Cache group priority vendor: {/ / key to entry the entry name defined in chunks: "initial", / / must choose three: "initial" | | "all" "async" (the default is async) test. / react | lodash /, / / verify the regular rules, if conform to extract the chunk name: "vendor", / / to cache that separates the chunk name minSize: 30000, minChunks: 1, enforce: True, maxAsyncRequests: 5, maxAsyncRequests: 5, // maxInitialRequests: 3, reuseExistingChunk: True // can set whether to reuse the chunk}}});Copy the code
#9, custom code compression tool
By default, WebPack4. x uses TerserPlugin for code compression.
/ / use the optimization. The minimizer. Use (WebpackPlugin, args); / / delete the config. Optimization. Minimizers. Delete an example (name) / / config. The optimization. The minimizer (' CSS ') .use(OptimizeCSSAssetsPlugin, [{ cssProcessorOptions: { safe: true } }]) // Minimizer plugins can also be specified by their path, allowing the expensive require()s to be // skipped in cases where the plugin or webpack configuration won't end up being used. config.optimization .minimizer('css') .use(require.resolve('optimize-css-assets-webpack-plugin'), [{ cssProcessorOptions: { safe: True}}]) // is to tap to modify the plugin parameter config.optimization.minimizer (' CSS '). Tap (args => [...args, {cssProcessorOptions: {safe: false } }])Copy the code
#10. Add a new Loader
First of all, please learn how to configure Webpack
Config.module.rule (name).use(name).loader(loader).options(options) // An example config.module.rule (' graphQL ') .test(/\.graphql$/).use(' graphqL-tag /loader').loader('graphql-tag/loader').end() // If not webpack-chain module:{ rules:[ { test:/\.graphql$/, use::[ { loader:"graphql-tag/loader" } ] } ] }Copy the code
#11. Modify Loader
// vue.config.js module.exports = { chainWebpack: Config => {config.module.rule ('vue').use('vue-loader').loader('vue-loader').tap(options => {// modify its options... return options }) } }Copy the code
Note that for CSS-related Loaders, we recommend using css.loaderoptions rather than directly chaining loaders. This is because there are multiple rules for each CSS file type, and css.loaderOptions ensures that you can affect all the rules in one place.
#Replace a Loader in a rule
// vue.config.js module.exports = { chainWebpack: Config => {const svgRule = config.module.rule(' SVG ') // Clear all existing loaders. // If you do not do this, the following loader will be appending to the existing loader for this rule. SvgRule. Use (' vue-SVG-loader ').loader(' vue-SVG-loader ')}} svgRule. Use (' vue-SVG-loader ').Copy the code
#13. Use WHEN to configure conditions
Consif. When (condition, truthyFunc falsyFunc) / / an example, when building production package add minify plug-in, or setting up the build type for the source - map / / devtool please see: https://www.webpackjs.com/configuration/devtool/ config .when(process.env.NODE_ENV === 'production', config => config.plugin('minify').use(BabiliWebpackPlugin), config => config.devtool('source-map') );Copy the code
#14. Use toString() to check the Webpack configuration of the chain
Note that the data generated with toString() cannot be used directly on WebPack.
config
.module
.rule('compile')
.test(/\.js$/)
.use('babel')
.loader('babel-loader');
config.toString();
/*
{
module: {
rules: [
/* config.module.rule('compile') */
{
test: /\.js$/,
use: [
/* config.module.rule('compile').use('babel') */
{
loader: 'babel-loader'
}
]
}
]
}
}
*/
Copy the code
#reference
- Vue-cli
- webpack-chain
If you find this article useful, please visit Star: mrGaogang.github. IO