Senior front-end software engineer knowledge organization packaging articles

1. Briefly introduce the configuration of webpack?

Taking the latest version 4.29.6 as an example, the basic configuration of webpack includes:

configuration describe

context

Base directory, absolute path , used to resolve the entry point entry and loader from the configuration

entry

The starting point or the starting point entry of the application. From this starting point, the application starts executing. If an array is passed, each item of the array will be executed.

Regarding the naming rules, if a string or string array (entry: [hot.js, index.js]) is passed in, the chunk will be named  main,chunk refers to the js file after the build is successfully packaged, such as packaged in the react technology stack out of main.js. If an object (entry:{index: index.js}) is passed in, each key (key) will be the name of the chunk, and the value describes the entry point of the chunk, such as index.js.

output

Located at the top-level key of the object (key), it includes a set of options that instruct webpack how to output and where to output your "bundles, assets, and anything else you package or load with webpack". Common configuration items are:

【path】The output directory corresponds to an absolute path , indicating the address where the packaged file is stored.

【filename】This option determines the name of each output bundle. These bundles will be written to the directory specified by the output.path option.

For example, for a single entry point, filename will be a static name filename: "bundle.js"; when multiple entry files are included, you can use [name].bundle.js, [id].bundle.js, etc. to set a unique file name .

[chunkFilename] This option determines the names of non-entry chunk files, which need to be generated at runtime according to the request sent by the chunk.

[publicPath] output.publicPath is an important option for on-demand-load or external resources (such as pictures, files, etc.). If you specify an incorrect value, you will receive a 404 error when loading these resources. In most cases, the value of this option will /end with , corresponding to the public directory in the project.

optimization The module that is independent from the plugin webpack.optimize.CommonsChunkPlugin, by removing the common module, the final synthesized file can be loaded once at the very beginning, and then stored in the cache for subsequent use. This leads to a speed increase, because the browser will quickly fetch the common code from the cache, instead of loading a larger file every time a new page is accessed.

module

These options determine how different types of modules or files in the project are handled. Common configuration items are:

strictExportPresence】是否将丢失的模块报出错误而不是警告。

[rules] Array of rules matching requests when creating a module. These rules are usually module (module) application loader, or modify the parser (parser). In short, it is to realize the conversion of module files.

plugins Plugin options are used to customize the webpack build process in various ways. webpack comes with various built-in plugins which can be accessed via webpack.[plugin-name]. Such as code compression, adding code header comments, etc.
resolve

resolver is a library to help find absolute paths to modules. A module can be used as a dependent module of another module, and then referenced by the latter, and the dependent module can be from the application code or a third-party library (library). Common configuration items are:

alias】Create  an alias of import or  require to make module import easier. For example, configure '@': path.resolve(__dirname, '../src'), when importing a file, @ means the root path.

[extensions] Automatically resolve certain extensions, enabling users to import modules without extensions.

modules】Tell webpack the directories that should be searched when parsing modules.

[ plugins] List of additional parsing plugins that should be used.

resolveLoader

resolve The object has the same set of properties, but only for parsing webpack's loader bundles.

devtool

A tool for debugging code after packaging, the production environment should be set to none
mode The current environment is development or production.

Other more detailed configurations can be viewed at  https://www.webpackjs.com/configuration/

2. What is the difference between plugin and loader? Which plugins and loaders in webpack have you used?

Main difference:

  • loader is mainly used to convert certain resource files. The loader describes how webpack handles non-javascript modules and includes these dependencies in compilation. Loaders can convert files from different languages ​​(such as TypeScript) to JavaScript, or convert inline images to dataURLs (such as Base64).
  • Plugin is used to extend the function of webpack, and also supplement the deficiency of loader. The purpose is to solve other things that the loader cannot achieve, from packaging optimization and compression, to redefining environment variables, it is powerful enough to handle a variety of tasks.

This answer varies from person to person, such as:

  • sass-loader, in the react scaffolding, has been integrated into the loaders configuration and can be used only after initialization. npm install node-sass.
  • stylus-loader needs to be configured by itself, and its function is similar to that of sass-loader.
  • BannerPlugin, add header comments to minified code.
  • CommonsChunkPlugin, which extracts commons code when packaging. In webpack4.x has been set as a separate configuration optimizatio

3. How are the plugins in webpack implemented?

The webpack plugin can be implemented simply by adding it to the plugin configuration item, such as:

const MyPlugin = require('myplugin')
const webpack = require('webpack')

webpack({
  ...,
  plugins: [new MyPlugin()]
  ...,
})

如自定义插件实现打包成功后生成一个文件filelist.md来显示文件列表:

function FileListPlugin() {}

FileListPlugin.prototype.apply = function(compiler) {
  compiler.plugin('emit', function(compilation, callback) {
    // 在生成文件中,创建一个头部字符串:
    var filelist = 'In this build:\n\n';
    
    // 遍历所有编译过的资源文件,
    // 对于每个文件名称,都添加一行内容。
    for (var filename in compilation.assets) {
      filelist += ('- '+ filename +'\n');
    }

    // 将这个列表作为一个新的文件资源,插入到 webpack 构建中:
    compilation.assets['filelist.md'] = {
      source: function() {
        return filelist;
      },
      size: function() {
        return filelist.length;
      }
    };

    callback();
  });
};

module.exports = FileListPlugin;

如果想更深入了解插件,可以看看这篇文章《探寻 webpack 插件机制》

4. 打包时Hash码是怎么生成的?

webpack打包出来的文件名称组成通常是[name].[hash码].后缀名,hash码的生存有三种方式:

  • hash。属于工程级别,所有打包出来的文件hash码都一样,只要一个文件修改,则所有文件的hash码也都会修改,这种hash码生存不利于缓存文件。
  • chunkhash。入口级别,chunkhash和hash不一样,它根据不同的入口文件(Entry)进行依赖文件解析、构建对应的chunk,生成对应的哈希值。可以理解为只要同一入口的文件,其生成的js和css文件hash码是一样的,只要一个改变另一个也会跟着改变,比如我只改变内容,不想改变样式,但实际上打包出来的文件名称都发生变化,不利于实现样式缓存。
  • contenthash。内容级别。由文件内容产生的hash值,内容不同产生的contenthash值也不一样,每个文件的hash都是独一无二的。目前最新版本的React脚手架技术栈就是使用这种方式打包,如:
filename: isEnvProduction
        ? 'static/js/[name].[contenthash:8].js'
        : isEnvDevelopment && 'static/js/bundle.js',
      // There are also additional JS chunk files if you use code splitting.
chunkFilename: isEnvProduction
        ? 'static/js/[name].[contenthash:8].chunk.js'
        : isEnvDevelopment && 'static/js/[name].chunk.js',

 

Guess you like

Origin blog.csdn.net/zeping891103/article/details/89225944