Webpack introduction

The website www.webpackjs.com/concepts/

WebPack can be viewed as a module baler: What it does is analyze the structure of your project, find JavaScript modules and other extension languages that browsers don’t run directly (Scss, TypeScript, etc.), and package them into a format that browsers can use.

Build is the transformation of source code into executable javascript, CSS, HTML code published online, including the following.

  • Code conversion: TypeScript to JavaScript, SCSS to CSS, etc.
  • File optimization: compress JavaScript, CSS, HTML code, compress merged images, etc.
  • Code splitting: Extract common code from multiple pages, extract code that does not need to be executed on the first screen and load it asynchronously.
  • Module consolidation: In a modular project there will be many modules and files that need to be grouped into a single file.
  • Auto refresh: Listen for changes to the local source code, and automatically rebuild and refresh the browser.
  • Code validation: Verifies compliance with specifications and unit tests before submitting code to the repository.
  • Automatic release: After updating the code, automatically build the online release code and transfer it to the release system.

Core WebPack concepts

  • Entry: Entry, Webpack performs the first step in the build starting with Entry, recursively looking for dependent modules to package.
  • Output: Outputs the result after Webpack has gone through a series of processes and produced the final desired code.
  • Loader: module converter, used to convert the original content of a module into new content as required.
  • Plugin: Extension Plugin that injects extension logic at specific points in the Webpack build process to change the build result or do what you want.

All modules in Webpack will convert all types of files into JS modules to load

Configuration webpack

Initialize the project to install dependency modules

npm init -y
npm i webpack webpack-cli webpack-dev-server -D
Copy the code

Webpack configuration file webpack.config.js

const path = require('path');

module.exports = {
  mode: 'development'.// Webpack starts from the entry
  entry: './src/index.js'.output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'bundle.js'}},Copy the code

mode

  • development
  • production

Production does some optimizations automatically

The output export

  • Path Output path of the package file
  • Filename: ‘bundle.[hash].[chunkHash].[contentHash].js’ output filename
  • Hash Hash value of a package
  • ChunkHash Hash of the module
  • ContentHash Hash of the content

Devtool Development tool

  • Eval wraps module code around eval
  • Source-map Generates a. Map file
  • Inline inserts. Map as a DataURI, does not generate a. Map file separately
  • Cheap does not contain column information, nor does it contain the Sourcemap for the Loader
  • Module contains sourcemap for loader

DevServer configures the development server

  • The directory in which the contentBase development server is started
  • Port the port number
  • The proxy agent
  devServer: {
    contentBase: path.resolve(__dirname, 'dist'),
    host: 'localhost'.port: 5000.proxy: {
      '/api': {
        target: 'http://localhost:4000'.pathRewrite: { '^/api': ' '}},}},Copy the code

Module Configures the loader for different files

Plugins configuration plug-in

  • NPM I html-webpack-plugin -d handles HTML templates
  • NPM I clean-webpack-plugin -d Clean directory plug-in before packaging

Compile and parse the React JSX syntax

  • npm i react react-dom -S
  • npm i babel-loader @babel/core @babel/preset-env @babel/preset-react -D

Loader (Loader

  • Test regular matching
  • Loader uses which loader to parse the matched file
  • Loader supports strings, arrays, and objects
  • Include folder
  • Exclude exclude folder

Load the React JS code conversion

    {
    test: /\.jsx? $/,
    use: {
        loader: 'babel-loader'.options: {"presets": ["@babel/preset-env"."@babel/preset-react"],}},include: path.join(__dirname,'src'),
    exclude:/node_modules/
}
Copy the code

Load the CSS from right to left and bottom to top

  • CSS analytical CSS – loader
  • Style-loader inserts CSS into HTML
    {
        test: /\.css$/,
        use: ['style-loader'.'css-loader'],}Copy the code

Load the SCSS

  • sass
  • sass-loader
    {
        test: /\.scss$/,
        use: ['style-loader', 'css-loader', 'sass-loader'],
    }
Copy the code

Handles CSS3 attribute prefixes

  • postcss-loader
  • autoprefixer
    {
        test: /\.css$/,
        use: ['style-loader', 'css-loader', 'postcss-loader'],
      }
Copy the code
  • Postcss Configuration file postcss.config.js
module.exports = {
  plugins: [require('autoprefixer')]};Copy the code

Loading image resources

  • Url-loader Solves the problem of importing image paths in CSS files
  • File-loader Encodes BASE64 images if the value is smaller than limit. If the value is larger than limit, file-loader is used to copy images
{
        test: /.(png|jpg|gif|svg)$/,
        use: [
          {
            loader: 'url-loader'.options: { limit: 1024 * 8}}},],Copy the code

Remove the CSS plug-in

  • Because CSS downloads and JS can be done in parallel, when an HTML file is large, we can pull out the CSS and load it separately
  • mini-css-extract-plugin
    plugins: [
        new MiniCssExtractPlugin({
          filename: '[name].css',] {})test: /\.css$/,
        use: [{ loader: MiniCssExtractPlugin.loader }, 'css-loader'.'postcss-loader'],}Copy the code

Compress JS and CSS

  • npm i uglifyjs-webpack-plugin terser-webpack-plugin optimize-css-assets-webpack-plugin -D
optimization: {
    minimizer: [
      new TerserPlugin({
        parallel: true.cache: true,}).// Compress CSS resources
      new OptimizeCSSAssetsPlugin({
        assetNameRegExp: /\.css$/g.// Cssnano is a CSS optimization and decomposition plugin for PostCSS. Cssnano takes well-formed CSS and goes through a number of optimizations to ensure that the final production environment is as small as possible.
        cssProcessor: require('cssnano'),})],}Copy the code

CSS and image are stored in separate directories

  • OutputPath outputPath
  • PublicPath specifies the path in HTML after the build
    output: {
        path: path.resolve(__dirname,'dist'),
        filename: 'bundle.js',
+        publicPath:'/'
    },

{
  test:/\.(jpg|jpeg|png|bmp|gif|svg|ttf|woff|woff2|eot)/,
  use:[
        {
          loader:'url-loader'.options: {limit: 4096,
+              outputPath: 'images',
+              publicPath:'/images'}}}]new MiniCssExtractPlugin({
+      filename: 'css/[name].css',
+      options: {
+        publicPath: '/', +}}),Copy the code

Resolve

  • Extensions do not need to be added to require or import extensions
  • Alias Configure aliases to speed up webPack module lookup
resolve: {
  extensions: [".js".".jsx".".json".".css"].alias: {
      "@": path.resolve(__dirname, 'src'),}},Copy the code

Code:Code portal