search
HomeWeb Front-endJS TutorialDetailed explanation of webpack4.0 packaging optimization steps

This time I will bring you a detailed explanation of the steps of webpack 4.0 packaging optimization. What are the precautions for webpack 4.0 packaging optimization? . The following is a practical case, let's take a look.

Webapck4 New Features Introduction - Reference Materials

Current dependent package versions

1. Optimize loader configuration

1.1 Narrow the file matching range (include/exclude)

Narrow the loader loading search range by excluding files under node_modules High probability hit File

  module: {
    rules: [
      {
        test: /\.js$/,
        use: 'babel-loader',
        exclude: /node_modules/, // 排除不处理的目录
        include: path.resolve(dirname, 'src') // 精确指定要处理的目录
      }
    ]
  }

1.2 Cache loader execution results (cacheDirectory)

cacheDirectory is a specific option of the loader, and the default value is false. The specified directory (use: 'babel-loader?cacheDirectory=cacheLoader') will be used to cache the execution results of the loader, reducing the Babel recompilation process during webpack build. If set to an empty value (use: 'babel-loader?cacheDirectory') or true (use: 'babel-loader?cacheDirectory=true') the default cache directory (node_modules/.cache/babel-loader) will be used, if in If the node_modules directory is not found in any root directory, it will downgrade and fall back to the operating system's default temporary file directory.

module: {
  rules: [
    {
      test: /\.js$/,
      use: 'babel-loader?cacheDirectory', // 缓存loader执行结果 发现打包速度已经明显提升了
      exclude: /node_modules/,
      include: path.resolve(dirname, 'src')
    }
  ]
}

2.resolve optimization configuration

2.1 Optimization module search path resolve.modules

Webpack's resolve.modules configures the location of the module library (i.e. node_modules). When import 'vue' appears in js, which is neither a relative nor an absolute path, it will be found in the node_modules directory. However, the default configuration will be found through upward recursive search, but usually there is only one node_modules in the project directory, and it is in the project root directory. In order to reduce the search scope, you can directly specify the full path of node_modules; similarly, for aliases ( alias) configuration, the same should be true:

const path = require('path');
function resolve(dir) { // 转换为绝对路径
  return path.join(dirname, dir);
}
resolve: {
  modules: [ // 优化模块查找路径
    path.resolve('src'),
    path.resolve('node_modules') // 指定node_modules所在位置 当你import 第三方模块时 直接从这个路径下搜索寻找
  ]
}

After configuring the location of the src directory, since the util directory is in src, you can use the following method to introduce the tools in util Function

// main.js
import dep1 from 'util/dep1';
import add from 'util/add';

2.2 resolve.alias Configure path alias

Create a path alias for import or require to ensure that module introduction becomes easier. The configuration item maps the original import path to a new import path through aliases. This optimization method will affect the use of Tree-Shaking to remove invalid code

For example, some common modules located in the src/ folder:

alias: {
 Utilities: path.resolve(dirname, 'src/utilities/'),
 Templates: path.resolve(dirname, 'src/templates/')
}

Now, replace the "use relative path when importing" method with something like this:

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

You can use the alias like this:

import Utility from 'Utilities/utility';
resolve: {
  alias: { // 别名配置 通过别名配置 可以让我们引用变的简单
    'vue$': 'vue/dist/vue.common.js', // $表示精确匹配
    src: resolve('src') // 当你在任何需要导入src下面的文件时可以 import moduleA from 'src/moduleA' src会被替换为resolve('src') 返回的绝对路径 而不需要相对路径形式导入
  }
}

Also in the given object Add $ at the end after the key to indicate an exact match:

alias: {
  util$: resolve('src/util/add.js')
}

This will produce the following results:

import Test1 from 'util'; // 精确匹配,所以 src/util/add.js 被解析和导入
import Test2 from 'util/dep1.js'; // 精确匹配,触发普通解析 util/dep1.js

2.3resolve.extensions

When introduced When the module does not have a file suffix, webpack will automatically parse the determined file suffix according to this configuration

  1. The suffix list should be as small as possible

  2. The most frequent Preface the

  3. export statement with the suffix

resolve: {
  extensions: ['.js', '.vue']
}

3.module.noParse

Modules that use noParse will not be parsed by loaders, so if the library we use is too large and does not contain import require and define calls, we can use this configuration to improve performance. , let Webpack ignore the recursive parsing of some files that do not use Modularization.

// 忽略对jquery lodash的进行递归解析
module: {
  // noParse: /jquery|lodash/
  // 从 webpack 3.0.0 开始
  noParse: function(content) {
    return /jquery|lodash/.test(content)
  }
}

4.HappyPack

HappyPack allows webpack to expand the execution process of the loader from a single process form to a multi-process mode, that is Decompose the task to multiple sub-processes for concurrent execution. After the sub-processes complete the processing, the results are sent to the main process. This speeds up code construction and is better used in combination with DLL dynamic link libraries.

npm i happypack@next -D

webpack.config.js

const HappyPack = require('happypack');
const os = require('os'); // node 提供的系统操作模块
 // 根据我的系统的内核数量 指定线程池个数 也可以其他数量
const happyThreadPool = HappyPack.ThreadPool({size: os.cpus().lenght})
module: {
  rules: [
    {
      test: /\.js$/,
      use: 'happypack/loader?id=babel',
      exclude: /node_modules/,
      include: path.resolve(dirname, 'src')
    }
  ]
},
plugins: [
  new HappyPack({ // 基础参数设置
    id: 'babel', // 上面loader?后面指定的id
    loaders: ['babel-loader?cacheDirectory'], // 实际匹配处理的loader
    threadPool: happyThreadPool,
    // cache: true // 已被弃用
    verbose: true
  });
]

happypack提供的loader,是对文件实际匹配的处理loader。这里happypack提供的loader与plugin的衔接匹配,则是通过id=happypack来完成。

npm run dev

5.DLL动态链接库

在一个动态链接库中可以包含其他模块调用的函数和数据,动态链接库只需被编译一次,在之后的构建过程中被动态链接库包含的模块将不会被重新编译,而是直接使用动态链接库中的代码。

  1. 将web应用依赖的基础模块抽离出来,打包到单独的动态链接库中。一个链接库可以包含多个模块。

  2. 当需要导入的模块存在于动态链接库,模块不会再次打包,而是去动态链接库中去获取。

  3. 页面依赖的所有动态链接库都需要被加载。

5.1 定义DLL配置

依赖的两个内置插件:DllPlugin 和 DllReferencePlugin

5.1.1 创建一个DLL配置文件webpack_dll.config.js

module.exports = {
  entry: {
    react: ['react', 'react-dom']
  },
  output: {
    filename: '[name].dll.js', // 动态链接库输出的文件名称
    path: path.join(dirname, 'dist'), // 动态链接库输出路径
    libraryTarget: 'var', // 链接库(react.dll.js)输出方式 默认'var'形式赋给变量 b
    library: '_dll_[name]_[hash]' // 全局变量名称 导出库将被以var的形式赋给这个全局变量 通过这个变量获取到里面模块
  },
  plugins: [
    new webpack.DllPlugin({
      // path 指定manifest文件的输出路径
      path: path.join(dirname, 'dist', '[name].manifest.json'),
      name: '_dll_[name]_[hash]', // 和library 一致,输出的manifest.json中的name值
    })
  ]
}

5.1.2 output.libraryTarget 规定了以哪一种导出你的库  默认以全局变量形式 浏览器支持的形式

具体包括如下:

  1. "var" - 以直接变量输出(默认library方式) var Library = xxx (default)

  2. "this" - 通过设置this的属性输出 this["Library"] = xxx

  3. "commonjs" - 通过设置exports的属性输出 exports["Library"] = xxx

  4. "commonjs2" - 通过设置module.exports的属性输出 module.exports = xxx

  5. "amd" - 以amd方式输出

  6. "umd" - 结合commonjs2/amd/root

5.1.3 打包生成动态链接库

webpack --config webpack_dll.config.js --mode production

在dist目录下 多出react.dll.js 和 react.manifest.json

  1. react.dll.js 动态链接库 里面包含了 react和react-dom的内容

  2. react.manifest.json 描述链接库(react.dll)中的信息

5.2 在主配置文件中使用动态链接库文件

// webpack.config.js
const webpack = require('webpack');
plugins: [
  // 当我们需要使用动态链接库时 首先会找到manifest文件 得到name值记录的全局变量名称 然后找到动态链接库文件 进行加载
  new webpack.DllReferencePlugin({
    manifest: require('./dist/react.manifest.json')
  })
]

5.3 将动态链接库文件加载到页面中

需要借助两个webpack插件

html-webpack-plugin 产出html文件

html-webpack-include-assets-plugin 将js css资源添加到html中 扩展html插件的功能

npm i html-webpack-plugin html-webpack-include-assets-plugin -D

配置webpack.config.js

const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlIncludeAssetsPlugin = require('html-webpack-include-assets-plugin');
pluings: [
  new webpack.DllReferencePlugin({
    manifest: require('./dist/react.manifest.json')
  }),
  new HtmlWebpackPlugin({
    template: path.join(dirname, 'src/index.html')
  }),
  new HtmlIncludeAssetsPlugin({
    assets: ['./react.dll.js'], // 添加的资源相对html的路径
    append: false // false 在其他资源的之前添加 true 在其他资源之后添加
  });
]

此时react.dll.js和main.js被自动引入到页面中,并且dll文件在main.js之前加载

 

6.ParallelUglifyPlugin

这个插件可以帮助有很多入口点的项目加快构建速度。把对JS文件的串行压缩变为开启多个子进程并行进行uglify。

cnpm i webpack-parallel-uglify-plugin -D
// webpck.config.js
const ParallelUglifyPlugin = require('webpack-parallel-uglify-plugin');
plugins: [
  new ParallelUglifyPlugin({
    workerCount: 4,
    uglifyJS: {
      output: {
        beautify: false, // 不需要格式化
        comments: false // 保留注释
      },
      compress: { // 压缩
        warnings: false, // 删除无用代码时不输出警告
        drop_console: true, // 删除console语句
        collapse_vars: true, // 内嵌定义了但是只有用到一次的变量
        reduce_vars: true // 提取出出现多次但是没有定义成变量去引用的静态值
      }
    }
  });
]

执行压缩

webpack --mode production

7.Tree Shaking

剔除JavaScript中用不上的代码。它依赖静态的ES6模块化语法,例如通过impot和export导入导出

commonJS模块 与 es6模块的区别

commonJS模块:

1.动态加载模块 commonJS 是运行时加载 能够轻松实现懒加载,优化用户体验

2.加载整个模块 commonJS模块中,导出的是整个模块

3.每个模块皆为对象 commonJS模块被视作一个对象

4.值拷贝 commonJS的模块输出和函数的值传递相似,都是值得拷贝

es6模块

1.静态解析 es6模块时 编译时加载 即在解析阶段就确定输出的模块的依赖关系,所以es6模块的import一般写在被引入文件的开头

2.模块不是对象 在es6里,每个模块并不会当做一个对象看待

3.加载的不是整个模块 在es6模块中 一个模块中有好几个export导出

4.模块的引用 es6模块中,导出的并不是模块的值得拷贝,而是这个模块的引用

7.1 保留ES6模块化语法

// .babelrc
{
  "presets": [
    [
      "env", {
        modules: false // 不要编译ES6模块
      },
      "react",
      "stage-0"
    ]
  ]
}

7.2 执行生产编译 默认已开启Tree Shaking

webpack --mode production

什么是Tree Shaking?

有个funs.js 里面有两个函数

// funs.js
export const sub = () => 'hello webpack!';
export const mul = () => 'hello shaking!';

main.js 中依赖funs.js

// main.js
import {sub} from './funs.js'
sub();

在main.js只使用了里面的 sub函数 默认情况下也会将funs.js里面其他没有的函数也打包进来, 如果开启tree shaking 生产编译时

webpack --mode production //此时funs.js中没有被用到的代码并没打包进来 而被剔除出去了

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

jQuery可见性过滤器使用案例详解

键值字符串如何转化为json字符串(附代码)

The above is the detailed content of Detailed explanation of webpack4.0 packaging optimization steps. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Web Speech API开发者指南:它是什么以及如何工作Web Speech API开发者指南:它是什么以及如何工作Apr 11, 2023 pm 07:22 PM

​译者 | 李睿审校 | 孙淑娟Web Speech API是一种Web技术,允许用户将语音数据合并到应用程序中。它可以通过浏览器将语音转换为文本,反之亦然。Web Speech API于2012年由W3C社区引入。而在十年之后,这个API仍在开发中,这是因为浏览器兼容性有限。该API既支持短时输入片段,例如一个口头命令,也支持长时连续的输入。广泛的听写能力使它非常适合与Applause应用程序集成,而简短的输入很适合语言翻译。语音识别对可访问性产生了巨大的影响。残疾用户可以使用语音更轻松地浏览

如何使用Docker部署Java Web应用程序如何使用Docker部署Java Web应用程序Apr 25, 2023 pm 08:28 PM

docker部署javaweb系统1.在root目录下创建一个路径test/appmkdirtest&&cdtest&&mkdirapp&&cdapp2.将apache-tomcat-7.0.29.tar.gz及jdk-7u25-linux-x64.tar.gz拷贝到app目录下3.解压两个tar.gz文件tar-zxvfapache-tomcat-7.0.29.tar.gztar-zxvfjdk-7u25-linux-x64.tar.gz4.对解

web端是什么意思web端是什么意思Apr 17, 2019 pm 04:01 PM

web端指的是电脑端的网页版。在网页设计中我们称web为网页,它表现为三种形式,分别是超文本(hypertext)、超媒体(hypermedia)和超文本传输协议(HTTP)。

web前端和后端开发有什么区别web前端和后端开发有什么区别Jan 29, 2023 am 10:27 AM

区别:1、前端指的是用户可见的界面,后端是指用户看不见的东西,考虑的是底层业务逻辑的实现,平台的稳定性与性能等。2、前端开发用到的技术包括html5、css3、js、jquery、Bootstrap、Node.js、Vue等;而后端开发用到的是java、php、Http协议等服务器技术。3、从应用范围来看,前端开发不仅被常人所知,且应用场景也要比后端广泛的太多太多。

Python轻量级Web框架:Bottle库!Python轻量级Web框架:Bottle库!Apr 13, 2023 pm 02:10 PM

和它本身的轻便一样,Bottle库的使用也十分简单。相信在看到本文前,读者对python也已经有了简单的了解。那么究竟何种神秘的操作,才能用百行代码完成一个服务器的功能?让我们拭目以待。1. Bottle库安装1)使用pip安装2)下载Bottle文件https://github.com/bottlepy/bottle/blob/master/bottle.py2.“HelloWorld!”所谓万事功成先HelloWorld,从这个简单的示例中,了解Bottle的基本机制。先上代码:首先我们从b

web前端打包工具有哪些web前端打包工具有哪些Aug 23, 2022 pm 05:31 PM

web前端打包工具有:1、Webpack,是一个模块化管理工具和打包工具可以将不同模块的文件打包整合在一起,并且保证它们之间的引用正确,执行有序;2、Grunt,一个前端打包构建工具;3、Gulp,用代码方式来写打包脚本;4、Rollup,ES6模块化打包工具;5、Parcel,一款速度极快、零配置的web应用程序打包器;6、equireJS,是一个JS文件和模块加载器。

web是前端还是后端web是前端还是后端Aug 24, 2022 pm 04:10 PM

web有前端,也有后端。web前端也被称为“客户端”,是关于用户可以看到和体验的网站的视觉方面,即用户所看到的一切Web浏览器展示的内容,涉及用户可以看到,触摸和体验的一切。web后端也称为“服务器端”,是用户在浏览器中无法查看和交互的所有内容,web后端负责存储和组织数据,并确保web前端的所有内容都能正常工作。web后端与前端通信,发送和接收信息以显示为网页。

深入探讨“高并发大流量”访问的解决思路和方案深入探讨“高并发大流量”访问的解决思路和方案May 11, 2022 pm 02:18 PM

怎么解决高并发大流量问题?下面本篇文章就来给大家分享下高并发大流量web解决思路及方案,希望对大家有所帮助!

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software