不经常更新的第三方库,比如 react,lodash,我们希望能和自己的代码分离开,如何处理?

1、准备

  1. import $ from 'jquery';
  2. console.log($);
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>webpack</title>
  7. </head>
  8. <body>
  9. <h1 id="title">hello html</h1>
  10. </body>
  11. </html>

2、webpack.dll.js

  1. /*
  2. 使用dll技术,对某些库(第三方库:jquery、react、vue...)进行单独打包
  3. 当你运行 webpack 时,默认查找 webpack.config.js 配置文件
  4. 需求:需要运行 webpack.dll.js 文件
  5. --> webpack --config webpack.dll.js
  6. */
  7. const { resolve } = require('path');
  8. const webpack = require('webpack');
  9. module.exports = {
  10. entry: {
  11. // 最终打包生成的[name] --> jquery
  12. // ['jquery'] --> 要打包的库是jquery
  13. jquery: ['jquery'],
  14. },
  15. output: {
  16. filename: '[name].js',
  17. path: resolve(__dirname, 'dll'),
  18. library: '[name]_[hash]' // 打包的库里面向外暴露出去的内容叫什么名字
  19. },
  20. plugins: [
  21. // 打包生成一个 manifest.json --> 提供和jquery映射
  22. new webpack.DllPlugin({
  23. name: '[name]_[hash]', // 映射库的暴露的内容名称
  24. path: resolve(__dirname, 'dll/manifest.json') // 输出文件路径
  25. })
  26. ],
  27. mode: 'production'
  28. };

1、结果

jquery与webpack.dll.js里面相匹配。
image.png
image.png

2、webpack.config.js

  1. const { resolve } = require('path');
  2. const HtmlWebpackPlugin = require('html-webpack-plugin');
  3. const webpack = require('webpack');
  4. const AddAssetHtmlWebpackPlugin = require('add-asset-html-webpack-plugin');
  5. module.exports = {
  6. entry: './src/index.js',
  7. output: {
  8. filename: 'built.js',
  9. path: resolve(__dirname, 'build')
  10. },
  11. plugins: [
  12. new HtmlWebpackPlugin({
  13. template: './src/index.html'
  14. }),
  15. // 告诉webpack哪些库不参与打包,同时使用时的名称也得变~
  16. new webpack.DllReferencePlugin({
  17. manifest: resolve(__dirname, 'dll/manifest.json')
  18. }),
  19. // 将某个文件打包输出去,并在html中自动引入该资源
  20. new AddAssetHtmlWebpackPlugin({
  21. filepath: resolve(__dirname, 'dll/jquery.js')
  22. })
  23. ],
  24. mode: 'production'
  25. };

1、结果

image.png
image.png

3、优化

当 DLL 需要更新的时候,比如 react 升级了,或者加入新的第三方库,都需要手动像下面这样编译一次 webpack —config webpack.dll.config.js。
每次打包的时候,只需要运行 webpack —config webpack.config.js

  1. const { resolve } = require('path');
  2. const HtmlWebpackPlugin = require('html-webpack-plugin');
  3. const DllLinkPlugin = require('dll-link-webpack-plugin')
  4. const AddAssetHtmlWebpackPlugin = require('add-asset-html-webpack-plugin');
  5. module.exports = {
  6. entry: './src/index.js',
  7. output: {
  8. filename: 'built.js',
  9. path: resolve(__dirname, 'build')
  10. },
  11. plugins: [
  12. new HtmlWebpackPlugin({
  13. template: './src/index.html'
  14. }),
  15. new DllLinkPlugin({
  16. config: require('./webpack.dll.js')
  17. }),
  18. new AddAssetHtmlWebpackPlugin({
  19. filepath: resolve(__dirname, 'dll/jquery.js')
  20. })
  21. ],
  22. mode: 'production'
  23. };

1、结果

image.png
image.png