Webpack three hash values

  • Hash: This is related to the build of the entire project. The hash value of the files generated by the build will be the same. Whenever a file changes in the project, the hash value of the entire project will change. (Usually not)
  • Chunkhash: Resolves dependent files based on different Entry files, builds corresponding chunks, and generates hash values.
  • Contenthash: Indicates the hash value generated by the file content. The contenthash value varies with the content.

__dirname etc.

  • __dirname: indicates the directory where the js is being executed.
  • __filename(represents the full path of the js currently being executed);
  • Path.join (‘/ directory 1’, ‘.. /’, ‘directory 3/ directory 4′,’ directory 5′); Merge directories, the result is “\ directory 3\ directory 4\ directory 5”;
  • Process.cwd () is the directory in which the current Node command is executed.
  • path.extname(filename); // Get the suffix name

css modules

CSS Modules is a solution to CSS namespaces as an alternative to Scope CSS

Interpolation in index.html

  • <%= VALUE %> used to do unescaped interpolation;
  • <% -value %> is used to do HTML escape interpolation; If the VALUE contains <> characters that need to be escaped;
  • <% expression %> is used to describe JavaScript flow control. Expression is a JS statement, including if and else.

Env environment variable

  • .env # is loaded in all environments
  • .env.local # is loaded in all environments, but is ignored by Git
  • .env.[mode] # load only in the specified mode
  • Env.[mode]. Local # is only loaded in the specified mode, but is ignored by Git
  • Variables added to webpack.config.js or chainWebpack’s config.plugin(‘define’).tap in vue.config.js have higher priority and will not be overridden by. Env
  • Mode can be a custom modevue-cli-service build --mode [mode]Command can be implemented in different modes with different environment variables. The corresponding NODE_ENV value needs to be specified in the.env.mode file, for example, NODE_ENV = ‘production’,

Different environment variables for different modes

  • For example, NPM run serve –aaa. The value in vue.config.js is as followslet tempO = JSON.parse(process.env.npm_config_argv).original[2]; orconst argArr = process.argv.splice(2);
  • To customize the NPM command, for example, “local”: “set VUE_APP_AAA=aaa && set BBB=qwer && NPM run serve”. In MAC shell, the corresponding command is “local”: “VUE_APP_AAA=aaa set BBB=qwer NPM run serve”;
  • Set up different. Env. [mode] files such as. Env.staging, and then customize the NPM command “build:stage”: “vue-cli-service build –mode staging”.

These methods can also be used with the following techniques

"bn": "npm run build && node replace"."serve": "node init && vue-cli-service serve".Copy the code

Determine if it is a production environment

process.env.NODE_ENV === ‘production’

Preview the dist package file locally

The local preview dist directory requires launching an HTTP server to access it (unless you’ve configured publicPath to a relative value), so opening dist/index.html directly with the file:// protocol won’t work. The easiest way to build in a local preview production environment is to use a Node.js static file server, such as Serve: NPM install -g Serve

Some common modification methods

Set up an SCSS public file

The vue. Config. Js

module.exports = {
    css: {
        loaderOptions: {
            scss: {
                prependData: "@import '~@/assets/style/public.scss';"}}}}Copy the code

Alias: {‘style’: resolve(‘static/style’)} @import “style/mixin.scss”; @import “~style/mixin.scss”; Css-related files need special processing

Adjust inline file size limits with chainWebpack

For example, the following code sets its limit to 10KB

// vue.config.js
module.exports = {
  chainWebpack: config= > {
    config.module
    .rule('images')
    .use('url-loader')
    .loader('url-loader')
    .tap(options= > Object.assign(options, { limit: 10240}}}))Copy the code

Add new environment variables via chainWebpack

// vue.config.js
module.exports = {
  chainWebpack: config= > {
    config.plugin('define').tap(args= > {
        let ori = args[0] ['process.env'];
        args[0] ['process.env'] = {
            ...ori,
            AA: JSON.stringify('<span>cscs</span>'),
            BB: 999.VUE_APP_UU: JSON.stringify('ppooii'),
            VUE_APP_UO: JSON.stringify('v_uuu'),}returnargs; }); }}Copy the code

Add a new JS loader via chainWebpack

// vue.config.js
const path = require('path');
module.exports = {
  chainWebpack: config= > {
    config.module.rule('js')
    .use('selfjs')
    .loader(path.resolve(__dirname, 'loader/selfjs.js'))
    .end()
  }
}
Copy the code

Contents of the selfjs.js file under loader:

module.exports = function loader(source) {
    console.log(source)
    source = source + ';;;;;;;; ';
    // return `export default ${ JSON.stringify(source) }`; / / the return value
    return source; / / the return value
    // return source; / / the return value
};
Copy the code

You can view the corresponding loader or plugin name in output.js

Webpack plugin introduction

The name of the role instructions
compression-webpack-plugin Gzip compression plug-in
webpack-bundle-analyzer Package analysis tool Cross-env needs to be re-installed
webpack-theme-color-replacer Plugin to change theme colors globally General background system use
webpack-obfuscator Code confusion
prerender-spa-plugin Handle seo for single page applications, pre-rendering It is better to use with vue-meta-info
copy-webpack-plugin Copy a single file or entire directory to the build directory
webpack-merge Merge webapck configuration items
html-webpack-plugin Working with HTML files
clean-webpack-plugin Clean up the previous package directory
mini-css-extract-plugin Unpack CSS plugins, because CSS is packaged in JS files by default The extract-text-webpack-plugin is no longer recommended
babel-loader Working with JS files Cooperate with @ Babel/core, @ Babel/preset – env
postcss-loader Handles CSS browser compatibility, such as adding the -webkit- prefix Cooperate with autoprefixer

Do not use CNPM

Set up an NPM image

  • npm config set registry registry.npm.taobao.org

  • npm config set disturl npm.taobao.org/dist

  • NPM config set electron_mirror npm.taobao.org/mirrors/ele…

  • NPM config set sass_binary_site npm.taobao.org/mirrors/nod…

  • NPM config set phantomjs_cdnurl npm.taobao.org/mirrors/pha…

  • Package. json files can only lock the larger version (the first digit of the version number), not later versions. Add package-lock.json at NPM 5.

  • NPM I handles and installs dependencies based on the contents of package-lock.json instead of package.json. CNPM I is not affected by package-lock.json and will only be downloaded according to package.json.

  • NPM I will generate package-lock.json. If it is removed, NPM I will generate package-lock.json. CNPM I does not generate package-lock.json.

  • CNPM I xxx@xxx will not be updated in package-lock.json. NPM I xxx@xxx will be updated in package-lock.json.

"dependencies": {
  "bluebird": "^ 3.3.4." "."body-parser": "~ 1.15.2"
}
Copy the code

Bluebird version number: ^3.3.4 Body-parse version number: ~1.15.2

Library version number details (^ and ~ difference)

  • Tilde (~) : It updates to the latest minor version (that number in the middle). In our example, body-Parser :~1.15.2. The library matches the latest version updated to 1.15.x, and if a new version is produced that is 1.16.0, it is not automatically upgraded. Tilde was once the default symbol for NPM installation, but has now been replaced with caret.
  • Caret (^) : This symbol is flexible and will update the current library version to the latest major version (the first digit). In our example, bluebird:^3.3.4. This library will match the latest version of 3.x.x, but it will not automatically update to 4.0.0.

Compare the NPM and yarn commands

npm yarn
npm install yarn
npm install react –save yarn add react
npm uninstall react –save yarn remove react
npm install react –save-dev yarn add react –dev
npm update –save npm update –save

NPM common commands

The command meaning instructions
npm config ls Check your NPM configuration
npm i -S packname Install project (run time, release to production) dependencies; Example: the vue. Corresponds to Dependencies in package.json npm install –save packname
npm i -D packname Installation project build (development time, “package” time) dependencies; Such as the Babel – loader. Corresponds to devDependencies in package.json npm install –save-dev packname
npm list -g –depth 0 View all installed global packages
npx vue-cli-service help View all available CLI commands vue-cli
npx vue-cli-service help build View all optional parameters of the NPM run build command vue-cli
npx vue-cli-service help inspect View all optional parameters of Vue Inspect vue-cli
vue inspect > output.js Print config to output.js in the same directory vue-cli
vue inspect –plugins Look at all the plugins you are using vue-cli
vue-cli-service serve –open Automatically opens the browser on startup vue-cli package.json
vue-cli-service build –report Generate report.html to help analyze package content vue-cli package.json
vue-cli-service build –report-json Generate report.json to help analyze package contents vue-cli package.json
vue-cli-service build –modern There are two versions of the application: a modern package for modern browsers that support ES Modules, and an older package for older browsers that don’t support the Legacy logo vue-cli package.json
set NODE_ENV=production && set AAA=123 && npm run build Set some environment variables and run a command that is written differently on the MAC NODE_ENV=production space XXXX vue-cli package.json
vue-cli-service build –mode cscs NPM run build –mode CSCS: NPM run build –mode CSCS vue-cli package.json

Refer more cli command: cli.vuejs.org/zh/guide/cl…

Reference: in 2020, there will be no webpack knock code is not fragrant.