The best practice of NPM Scripts and Webpack comprehensive configuration summary of webpack engineering practice

1. Use NPM Scripts to manage development commands

  1. Use NPM Scriptsto configure the development of command, that is package.jsonthe scriptsfield, so even if we modify the script even switch Webpackto other packaging tool for the rest of the team, using commands remain the same, the proposed commands include:
  • npm start: Equivalent npm run start, used to develop commands to quickly start local development services;
  • npm run build: Used for packaging in the production environment;
  • Other commands, similar npm run test/lint, etc., can be added according to the relevant
  1. In package.jsonuse cross-envto distinguish the environment, a look at the following example:
{
    
    
    // ...
    "scripts": {
    
    
        "start": "cross-env NODE_ENV=development webpack --config webpack.config.dev.js --mode development",
        "build": "cross-env NODE_ENV=production webpack --config webpack.config.prod.js --mode producation",
        "analyzer": "cross-env NODE_ENV=production webpack --config webpack.config.analyzer.js --mode producation",
        "lint": "lint-staged"
    }
    // ...
}

Two, Webpack distinguishes multi-environment configuration

  1. Distinguishing production and development environment configuration, and general packaging configuration, i.e. Webpackthe configuration file is divided into:
  • General arrangement webpack.config.base.js;
  • Development environment configuration webpack.config.dev.js;
  • Production environment configuration webpack.config.prod.js;
  1. webpack.config.base.js
    common configuration webpack.config.base.jsfor common configuration, e.g. entry、loader 和 pluginthe like, but some need to cross-envpass NODE_ENVperform configuration environment variables such as: NODE_ENV=developmentthe time used style-loader, and productionwhen used mini-css-extract-pluginin loaderthe production environment CSSgenerates a separate CSSfile ;
// webpack.config.base.js
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const isProduction = process.env.NODE_ENV === 'production';
module.exports = {
    
    
    // ...
    module: {
    
    
        rules: [
            {
    
    
                test: /\.css?$/,
                use: [
                    {
    
    
                        loader: isProduction ? MiniCssExtractPlugin.loader : 'style-loader'
                    },
                    {
    
    
                        loader: 'css-loader',
                        options: {
    
    
                            importLoaders: 1,
                            sourceMap: !isProduction
                        }
                    },
                    {
    
    
                        loader: 'postcss-loader',
                        options: {
    
    
                            sourceMap: !isProduction
                        }
                    }
                ]
            }
        ]
    }
    // ...
};
  1. webpack.config.dev.js
    development environment configuration webpack.config.dev.jsmainly for the development environment configuration, mainly devServer, API mockand other related configuration, which is part of the configuration focusing on efficiency, speed optimization package is also very important.

  2. webpack.config.prod.js
    webpack.config.prod.js for production configuration, this part of the line focus is optimal configuration package configuration, comprising splitChunks, resource compression, CDNpath configuration (the outputconfiguration), and other configuration may also be in the terser-webpack-pluginforced removal of some of the configuration forget Deleted debugging information: for example debugger、alert.

Note that the production environment is not recommended package generation sourcemap, if generated and do not upload to the online environment, because if sourcemapafter on-line, will be equal to others through Chromeother tools to directly view the source code line, which is very dangerous! But if you use a similar project Sentryis JavaScriptbeing given collection and analysis platform, we can sourcemapgo through Webpackto generate, remember to delete these files in the package on the line, preventing uploaded to online after uploading to the corresponding platform!

  1. webpack.config.analyzer.js
    In addition to these three profiles, in order to help us analyze the code package is reasonable to do a split, we can add a webpack.config.analyzer.js, this configuration is actually inherited webpack.config.prod.js, then add webpack-bundle-analyzerthe plugin configuration.

  2. Use webpack-mergemanagement configuration file relationships
    Webpackafter splitting profile, each have a dependency relationship between the specific relationship is as follows:

  • webpack.config.dev.jsThey are merged webpack.config.base.jsand their configuration;
  • webpack.config.prod.jsMerger webpack.config.base.jsand their configuration;
  • webpack.config.analyzer.jsMerger webpack.config.prod.jsand their configuration, and webpack.config.prod.jsis from webpack.config.base.js.
  1. If this configuration to maintain the relationship, then you need to use webpack-mergethis tool library, webpack-mergemainly to provide a Webpackconfiguration object Mergefunction to merge two configuration, similar to the Object.assignfunction of the function. As webpack.config.analyzer.jslook at webpack-mergehow to use:
const merge = require('webpack-merge');
const prodWebpackConfig = require('./webpack.config.prod.js');
const {
    
    BundleAnalyzerPlugin} = require('webpack-bundle-analyzer');

module.exports = merge(prodWebpackConfig, {
    
    
    // 增加 webpack-bundle-analyzer 配置
    plugins: [new BundleAnalyzerPlugin()]
});

3. Reasonable use of split Chunks

  1. In use splitChunksmainly to the size of a reasonable division of resources, improve the cache hit rate, thereby reducing the load time resources on the division of rationality must pay attention to grasp the intensity, too thin can not take advantage of HTTP Cache, too thick will lead to slow loading this Degrees are not generally defined, but generally speaking, the code can be split according to the following three principles:
  • Frequency of change;
  • Page Router;
  • Separation of movement and static.
  1. Change the frequency
    of code change according to the frequency used splitChunksto split, these are not about to frequent changes of common frameworks and libraries put together as a commoncode, and then the business code split between pages in accordance with the public part and the private part

  2. After
    the framework and library code that the page router does not change frequently are split, the rest is business code. The business code can be split together according to the common code between different pages, so that you can ensure that the framework code and the library code can be combined with one page. The common code is cached in the browser, and access to the second page will not increase the frame code and common code page request.

  3. Separation of
    dynamic and static refers to the fact that (使用import()或者require.ensure())the module code in the page that is not used frequently or needs to be dynamically and asynchronously loaded can be split into their own separately chunks, which ensures the speed of the first screen of the page. Further similar Vue、Reactsuch application a single page, the page Routercode between are asynchronously loaded, the entire page will be the first entry of the current page and a large frame entered code is loaded, so when the page click jump requires only two dynamic loading the corresponding Routercode to the.

Four, specify the hash value of the chunk

  1. Packaged in a production environment, the configuration file must be filenamethe hashrecommended hashconfiguration rules are as follows:
  • JavaScriptFile usage [chunkhash]:;
  • CSSFile usage [contenthash]:;
  • Other static resources used: [hash]such as images, fonts, etc., in url-loaderthe configuration[hash]

Five, best practices at the grammatical level

  1. The use of ES6 Modulesgrammar, in order to ensure that Tree-Shakingwork.

  2. Fair use Ployfill, it is recommended to use @babel/preset-envthe useBuiltIns='usage'program.

  3. Rational use of Webpackmagic comments (magic comments), such as: use dynamically loaded modules webpackChunkNameare named, you can also use significant resources webpackPrefetchahead of the pre-loaded.

  4. Use a reasonable version of the framework or class library, for example:

  • LodashUse lodash-esversion and use by the module;
  • MomentjsUsed date-fnsin place of, and use by the module;
  • Moving the page using Zeptoin place jQuery;
  • Vue、San、ReactChoose the right kind of framework library builds the actual situation, in order to Vue, for example, actually builds include browser version, ESMversion, UMDmultiple version, the full version, etc.

Six, other best practices for Webpack configuration

  1. Production environment using mini-css-extract-pluginthe export CSSdocuments;
  2. Production environments compression, comprising JavaScript、CSS、图片、SVGthe like;
  3. The rational allocation of search path, reducing search time, such as setting alias, add the path of the project, the investigation node_modulesto find and so on;
  4. In rulethe configuration, there are test、include、excludethree possible configuration of the control range, best practice:
  • Only in testand file name matching using regular expressions;
  • In includeand excludeusing an absolute path array;
  • Try to avoid it excludeand prefer to use it include.
  1. iconImage files much use CSS Spriteto merge pictures, to prevent setting url-loaderand svg-url-loaderthe limitvalue of unreasonable, resulting in iconfiles in a Base64way the introduction CSSfile, causing CSSthe file is too large.

Seven, other best practices

  1. Standardized Gitworkflow:
  • Use Git Hook, similar to the Huskytype of Git Hooklibrary that can help us before each submission (pre-commit)automatically do the lintchecks;
  • Use Commitizento regulate Gitthe submission Commit Log;
  1. Component-based development, public UIassemblies, public library building; here that the more abstract, the need for specific projects to divide, for example, we can be multiple pages common UIabstracted components; can also build up a common tool library, similar to Lodashthat Class library

  2. Choose a handy CSSpre-language Sass、Less、Stylus, only the team can easily use;

  3. Specify rules and conventions, including code specifications, directory structure, document specifications, etc.;

  4. Separate front and rear ends, select the appropriate Mockprogram;

  5. Make best practices into scaffolding for standard projects, and use scaffolding tools to create new projects;

  6. Abstract solutions, integrated into the Webpackconfiguration, even based on Webpackdoing their best practices tool chain.

Guess you like

Origin blog.csdn.net/weixin_42614080/article/details/110016633