Webpack configuration details

entry

const { resolve } = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

String --> './ SRC /index.js' Single entry is packaged to form a chunk. Output a bundle file. In this case, the default name of chunk is main 2. array -> ['./ SRC /index.js', './ SRC /add.js']. --> Hot HTML updates are enabled only in HMR. The chunk name is key --> special usage {// All the import files will end up as a chunk, and only one bundle will be exported. Index: ['./ SRC /index.js', './ SRC /count.js'], // form a chunk and output a bundle file. add: './src/add.js' } */

module.exports = {
  entry: {
    index: ['./src/index.js'.'./src/count.js'].add: './src/add.js'
  },
  output: {
    filename: '[name].js'.path: resolve(__dirname, 'build')},plugins: [new HtmlWebpackPlugin()],
  mode: 'development'
};
Copy the code

Attention ⚠ ️

  • If the entry starts with a string, it is a single entry, packaged as a chunk, and exported as a bundle file. The default name of chunk is main.
  • If the entry point is an array, it will be multiple entries. However, all the entry files will eventually form a chunk, and only a bundle file will be exported. HTML hot updates are only enabled in the HMR function.
  • If the entry starting point is an object, it is also multi-entry. At this point, several import files form several chunks and export several bundles. In this case, the chunk name is key.

output

const { resolve } = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './src/index.js'.output: {
    // File name (specify name + directory)
    filename: 'js/[name].js'.// Output file directory (public directory for future output of all resources)
    path: resolve(__dirname, 'build'),
    / / all resources into public path prefix -- > 'imgs/a. pg' - > '/ imgs/a. pg'
    publicPath: '/'.chunkFilename: 'js/[name]_chunk.js'.// The name of the non-entry chunk
    // library: '[name]', // the name of the variable exposed throughout the library
    // libraryTarget: 'window' // To which browser the variable name is added
    // libraryTarget: 'global' // to which node the variable name is added
    // libraryTarget: 'commonjs'
  },
  plugins: [new HtmlWebpackPlugin()],
  mode: 'development'
};
Copy the code

Attention ⚠ ️

  • publicPath: '/'Introduce a common path prefix for all resources.
  • chunkFilenameSet the non-import chunk name.
  • library: '[name]'Is the name of the variable exposed throughout the library,libraryTargetDecide on which variable names to add.

module

const { resolve } = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './src/index.js'.output: {
    filename: 'js/[name].js'.path: resolve(__dirname, 'build')},module: {
    rules: [
      // Loader configuration
      {
        test: /\.css$/.// Multiple loaders use use
        use: ['style-loader'.'css-loader'] {},test: /\.js$/.// Exclude js files under node_modules
        exclude: /node_modules/.// Check only js files under SRC
        include: resolve(__dirname, 'src'),
        // Priority execution
        enforce: 'pre'.// The execution is delayed
        // enforce: 'post',
        // Single loader uses loader
        loader: 'eslint-loader'.options: {}}, {// Only one of the following configurations takes effect
        oneOf: []}]},plugins: [new HtmlWebpackPlugin()],
  mode: 'development'
};
Copy the code

Attention ⚠ ️

  • The value of the exclude attribute is the file to exclude. Check only the files specified by include.
  • enforce: 'pre'For priority execution,enforce: 'post'To delay execution.

resolve

const { resolve } = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './src/js/index.js'.output: {
    filename: 'js/[name].js'.path: resolve(__dirname, 'build')},module: {
    rules: [{test: /\.css$/,
        use: ['style-loader'.'css-loader']]}},plugins: [new HtmlWebpackPlugin()],
  mode: 'development'.// Parse the module's rules
  resolve: {
    // Configure the parsing module path alias: Advantage -> abbreviated path Disadvantage -> Path is not prompted
    alias: {
      $css: resolve(__dirname, 'src/css')},// Omit the file path suffix
    extensions: ['.js'.'.json'.'.jsx'.'.css'].// Tells Webpack which directory to look for
    modules: [resolve(__dirname, '.. /.. /node_modules'), 'node_modules']}};Copy the code

Attention ⚠ ️

  • The resolve property sets the rules for resolving modules.aliasSet the path alias of the resolution module. The advantage is that the path can be abbreviated, but the disadvantage is that the path does not prompt.extensionsOmit file path suffix,modulesTell WebPack which directory the parsing module is looking for.

dev server

const { resolve } = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './src/js/index.js'.output: {
    filename: 'js/[name].js'.path: resolve(__dirname, 'build')},module: {
    rules: [{test: /\.css$/,
        use: ['style-loader'.'css-loader']]}},plugins: [new HtmlWebpackPlugin()],
  mode: 'development'.resolve: {
    alias: {
      $css: resolve(__dirname, 'src/css')},extensions: ['.js'.'.json'.'.jsx'.'.css'].modules: [resolve(__dirname, '.. /.. /node_modules'), 'node_modules']},devServer: {
    // Directory to run the code
    contentBase: resolve(__dirname, 'build'),
    // Monitor all files in the contentBase directory and reload them if they change
    watchContentBase: true.watchOptions: {
      // Ignore the file
      ignored: /node_modules/
    },
    // Start gzip compression
    compress: true./ / the port number
    port: 5000./ / domain name
    host: 'localhost'.// Automatically open the browser
    open: true.// Enable HMR
    hot: true.// Do not display startup server logs
    clientLogLevel: 'none'.// Do not display anything except some basic startup information
    quiet: true.// If something goes wrong, do not display it in full screen
    overlay: false.// Server proxy --> Resolve cross-domain issues in the development environment
    proxy: {
      // Once devServer(5000) receives a request for/API/XXX, it forwards the request to another server (3000).
      '/api': {
        target: 'http://localhost:3000'.// the request path is rewritten: / API/XXX --> / XXX (/ API)
        pathRewrite: {
          '^/api': ' '}}}}};Copy the code

Attention ⚠ ️

  • watchContentBase: trueIndicates that all files in the contentBase directory are monitored and reloaded if the file changes.watchOptionsSet in theignoredYou can ignore to monitor changes to certain files.
  • clientLogLevel: 'none'Do not display logs about starting the server.quiet: trueIndicates that no information is displayed except some basic startup information.overlay: falseIf an error occurs, do not display it in full screen.
  • proxyServer proxies are configured to address cross-domain issues in a development environment. There is cross-domain between browser and server, there is no cross-domain problem between server and server. The code runs through a proxy server, and there is no cross-domain between the proxy server and the server, so the request succeeds. The proxy server responds to the request to the browser to solve cross-domain problems in the development environment.

optimization

const { resolve } = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
// Import plug-ins
const TerserWebpackPlugin = require('terser-webpack-plugin')

module.exports = {
  entry: './src/js/index.js'.output: {
    filename: 'js/[name].[contenthash:10].js'.path: resolve(__dirname, 'build'),
    chunkFilename: 'js/[name].[contenthash:10]_chunk.js'
  },
  module: {
    rules: [{test: /\.css$/,
        use: ['style-loader'.'css-loader']]}},plugins: [new HtmlWebpackPlugin()],
  // Make sense in a production environment
  mode: 'production'.resolve: {
    alias: {
      $css: resolve(__dirname, 'src/css')},extensions: ['.js'.'.json'.'.jsx'.'.css'].modules: [resolve(__dirname, '.. /.. /node_modules'), 'node_modules']},optimization: {
    splitChunks: {
      chunks: 'all'
      // The default value is not ~
      MaxSiza: 0, // Max minChunks: 1, // Chunks to be extracted must be referred to in at least one time. MaxAsyncRequests: MaxInitialRequests: 3, // maxInitialRequests: 3, // automaticNameDelimiter: '~', // name connecter name: True, // Groups that split chunks // node_modules files are packaged into vendors group chunks using the naming convention cacheGroups: {// Vendors group chunks can be vendors group chunks. --> vendors~xxx.js // Satisfy the common rules above, e.g., be larger than 30KB and be referenced at least once. Vendors: {test: /[\\/]node_modules[\\/]/, // Priority: -10}, default: {// Chunks to be extracted are referenced minChunks at least 2 times: 2, // Priority: -20, // If the current module to be packaged is the same module that has already been extracted, it will be reused instead of reuseExistingChunk: true}}*/
    },
    // Package the hash of the current module into a single file runtime
    // Resolve: Modifying file A causes file B's contenthash to change
    runtimeChunk: {
      name: entrypoint= > `runtime-${entrypoint.name}`
    },
    minimizer: [
      // Configure the compression scheme for the production environment: JS and CSS
      new TerserWebpackPlugin({
        // Enable caching
        cache: true.// Enable multi-process packaging
        parallel: true./ / start the source - the map
        sourceMap: true}}})];Copy the code

Attention ⚠ ️

  • splitChunksHelp extract common code into a separate chunk package.
  • runtimeChunkPackage the hash of the current module to record other modules as a separate file (runtime file). Name: entryPoint =>runtime-${entrypoint.name}After the configuration, only the A file and runtime file are generated when the A file is changed.
  • minimizerThis section describes how to compress JS files and CSS files in the production environment. You need to installterser-webpack-pluginThe plug-in.