webpack common configuration information

1. devtool code debugging

1. under the mode of production

source-map: generate a map file, source positioned directly ranks

✅ can use this mode for testing server

cheap-source-map: only target line, and the code only target transcoding babel

cheap-module-source-map: only target the line, but you can navigate to the source

2. Under development model

eval: positioning the compiled code

cheap-eval-source-map: target line after transcoding babel

cheap-module-eval-source-map: positioning the source line

eval-source-map: to locate the source of the ranks

✅ recommended to use this method

line- * slow mode, regardless of

2. Application of third-party libraries

1. webpack.ProvidePlugin

In the case of each module similar lodash frequently used, in order to avoid introducing manually every time, the plug may be used to achieve all of the modules incorporated in the automatic document. Repeating the optimization problem only introduced directly introduced into the same volume and packaging.

    new webpack.ProvidePlugin({
      _: "Lods' 
    });

Each module corresponds to the default execution in the introduction, the user can directly use.

import _ from 'lodash';

This method is not global variables ❎

2. expose-loader

The library is introduced to avoid duplication method using a high frequency. And it can be used as a global variable. Very handy for debugging. It can be used directly in the console.

In the entrance files:

// must be The require 
The require ( 'EXPOSE-Loader _ lodash?!' );
 // front is a global variable name;!! After the library name is

You can then use window._ direct access.

3. externals

When you have third-party libraries from outside the CDN, etc., if the code and the manual introduction of the same library, this configuration allows webpack not packaged configuration of third-party libraries.

 externals: {
    lodash: '_' // : before the key is the name of the library; followed by the name of the global variable 
  }

Want to work, it must be introduced in html CDN

<script src="https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js"></script>

As above, even if the module is introduced manually, or use it to enter WebPACK encapsulated

_ from Import 'lodash'; // ignored introduced lodash library 

const A = _.join ([ 'A', 'B'], '~');

4. html-webpack-externals-plugin

3, the need to introduce CDN file in html file. If you do not want to manually introduced directly generate configuration, the plug may be used.

⚠️ the plug must be re-instantiated after html-webpack-plugin plug instantiated

new HtmlWebpackPlugin({
}),
new HtmlWebpackExternalsPlugin({
  externals: [
    {
      Module: "Lods" ,
      global: '_',
      entry: 'https://cdn.jsdelivr.net/npm/[email protected]/lodash.min.js'
    }
  ]
}),

3. Add the code package of notes

new webpack.BannerPlugin('Lyra'),

4. Copy static files (txt / doc, etc.)

    new CopyWebpackPlugin([{
      from: path.join(__dirname, './src/assets'),
      to: path.join(__dirname, './dist/assets')
    }]),

5. devServer realize proxy agent, and the analog server

devServer: {
    contentBase: path.join(__dirname, 'dist'),
    Port: 8080 , 
   Host: 'localhost',
the compress: to true, // enable gzip compression before (App) {
// devserver express itself is a server, app is the corresponding app; before refers performed before app.listen app.get ( '/ API / User', (REQ, RES) => { res.json([{ a: 'lyra' }]); }); }, proxy: { '/api': { target: 'HTTP: // localhost3000', // proxy local service to the destination server; equivalent nginx, cross-domain no problem pathRewrite: { '^ / API': '' // rewriting path; such as: / api / User -> / User } } } },

6. webpack-dev-middleware analog implementation webpack-dev-server

const express = require('express');
const WebpackDevMiddleware = require('webpack-dev-middleware');
const webpack = require('webpack');
const webpackConfig = require('./webpack.config.js');


App const = Express ();
 // Returns a compiled object 
const = Compiler WebPACK (webpackConfig);
 // 1. Use webpack-dev-middleware plug-in starts compiling 
// 2. This plug in response to client requests package file 
app. use (WebpackDevMiddleware (compiler, {} ));

app.get('/api/user', (req, res) => {
  res.json([{ a: 'name' }]);
});

app.listen(5000);

Start command

  "scripts": {
    "node": "node devServer.js",
    "build": "webpack",
    "dev": "webpack-dev-server --open"
  },

7. The parsing rules resolve module

1. extensions

When the import documents not written extension, according to the rules extentsions set for file search.

module.exports = {
  ...
  resolve: {
     extensions: ['.js', '.jsx', '.json']
  }  
}

2. alias

Find the path to define aliases, speed up file search speed.

For the introduction npm module installed, look for it in accordance with the rules, click Find Now. Finding the relative path, relative path will follow the rules, click Find Now.

Alias ​​can follow the path specified by defining lookup alias directly, avoiding the time consuming path resolution.

module.exports = {
  //...
  resolve: {
    alias: {
      Utilities: path.resolve(__dirname, 'src/utilities/'),
      Templates: path.resolve(__dirname, 'src/templates/')
    }
  }
};

Before the introduction alias:

import Utility from '../../utilities/utility';

Following the introduction of

import Utility from 'Utilities/utility';

In addition, the last with $ alias, said an exact match, ie using only the alias, not the other match.

module.exports = {
  //...
  resolve: {
    alias: {
      xyz$: path.resolve(__dirname, 'path/to/file.js')
    }
  }
};

Example:

Test1 from Import 'XYZ'; // exact match, according to resolve the alias 
; Import Test2 from 'XYZ / file.js' // do not match exactly, according to the original parsing rules resolve

3. modules

Module specified search, you can also add other modules need to look at the default rule

module.exports = {
  //...
  resolve: {
    modules: [ 'the node_modules', 'myloaders'] // The latter is custom module 
  }
};

4. mainFields

Find a defined sequence entry file field

= module.exports {
   // ... 
  Resolve: { // definition of the browser in the field to find package.json ... 
    mainFields: [ 'browser', 'Module1', 'main' ]
  }
};

5. mainFiles

When parsing a folder directory, looks for files in the folder according to the field

module.exports = {
  //...
  resolve: {
    mainFiles: [ 'index'] // may be modified to other main.js 
  }
};

8.resolveLoaders

With the properties and rules resolve, the processing corresponding to the loader module lookup rules.

module.exports = {
  //...
  resolveLoader: {
    modules: ['node_modules'],
    extensions: ['.js', '.json'],
    mainFields: ['loader', 'main']
  }
};

When the resolution in accordance with the rules in the module using loaders, find loader module in accordance with the definition of default discovery rules resolveLoader in.

9. custom global variables webpack.DefinePlugin

Contents of the string corresponding to the plug-in, will be treated as parsing code snippet. Corresponding to the variable value if a non-serialized string, through JSON.stringify ().

    new new webpack.DefinePlugin ({
       "PRODUCTION": the JSON.stringify ( to true ),
       "the AUTHOR" : {
         "the USER": the JSON.stringify ( 'Lyra') // String also need to be serialized, or treated according to the expression 
      }
    }),

10. Environment variables process.env.NODE_ENV

You can get the current value of the item mode by accessing process.env.NODE_ENV code.

application:

The package may be a function of the value to achieve different performance under different environments.

oldLog = const the console.log;
 // overwrite the original log function of 
the console.log = function newLog () {
   IF (process.env.NODE_ENV === 'Development' ) {
    oldLog ( 'development environment printing log' );
  }
};

// use, introduced into the document 
Import './console' ;

console.log("node_env", process.env.NODE_ENV);

11. glob match multiple entry file

glob is a tool for matching files.

above sea level and globe

If you want a multiple entry documents, the use of multiple html template file. We can import documents into a unified file entries; the unified template file into the templates folder. And the name of the correspondence.

No need to add one html-webpack-plugin plugin. Can batch operations.

const glob = require('glob');

Files const = glob.sync ( './ the src / entries It / JS *.'); // for a matching all file paths 
const entries It = {};
const templates = [];
files.forEach((file) => {
  fileName const = path.basename (File, '.js'); // Get the name of the file, without extension 
  entries It [fileName] = File;
  templates.push(new HtmlWebpackPlugin({
    Template:. ` / the src / Templates / .html`} $ {fileName,
     filename:` $ {fileName .html`},
     // the hash: to true, 
    of chunks are: [fileName], // the specified block of each chunk, otherwise, all the chunk are incorporated 
    chunksSortMode: 'manual'
  }));
});

12. Log Optimization stats

Most print log compile time webpack is invalid log, we have the code by setting the value of the stats show custom.

stats default is "normal".

module.exports = {
  //...
  stats: 'normal'
};

It may also be other values, such as

Errors-only 1.         // Print errors only 
2. Represents warnings errors- // errors and warnings 
3. verbose             // print all the information 
4. minimal             // print only error and new compiler 
5. none                 // does not print

If you want more clearly, you can use friendly-errors-webpack-plugin plugin (not very useful).

module.exports = {
  // ...
  plugins: [
    new FriendlyErrorsWebpackPlugin(),
  ],
}

13. compatibility issues polyfill ES6 other new API's

Generally recommended to use babel-polyfill, usage

import 'babel-polyfill';

However, this method will increase the volume of packed files, but also packaged for unwanted browser.

To solve these problems, you can use

<script src="https://polyfill.io/v3/polyfill.min.js/"></script>

The interface may require return polyfills according UserAgent. If Chrome browser will return empty content, because it does not require polyfills.

13. stats.json

npx webpack --profile --json > stats.json

By name generation stats.json file, which contains all the information packed. There are several attributes:

1. chunks

Code block. Ways to generate code:

1 generates a corresponding entry file chunk

output: {
    filename: '[name].[contenthash].js'  //hot:true下不能contenthash
}

2. Dynamic import module will generate a corresponding chunk (import ())

Such block chunk following naming
import(/* webpackChunkName: "example" */'./example')

3. splitChunk code division generates the chunk (block)

optimization: {
  splitChunks: {
    Cache groups: {
      vendors: {
        of chunks are: 'Initial', // must, by default async (import ()); initial synchronization is not set this value does not generate the code block 
        name: 'vendors', // set the block name 
        test: / node_modules / , // specifies the module to be packaged 
        the minSize: 50 * 1024,   // packed minimum volume 
        priority: 1
      }, 
      commons: {
        chunks: 'initial',
        name: 'commons',
        test: /src/,
        minChunks: 2, // at least one module is minChunks cited 
        priority: 2
      }
    }
  }
}, 

2. modules

Everything in webpack the module. Each js, css, image, etc. are modules.

webpack itself only recognizes js file for any non-js files are required to compile loader, it will eventually be compiled into js output.

3. assets

All files are generated final packaged assets.

 

Guess you like

Origin www.cnblogs.com/lyraLee/p/12042140.html