在webpack进行打包的时候,对于react、react-dom、vue、vuex等不会改变的依赖,和我们自己的代码分开打包,这样当我们修改自己的代码的时候,webpack只需要打包我们自己的代码,而第三方依赖第一次打包后,如果没有升级或者其他改变,那么就不需要在打包了,这样可以提高打包的速度
入口文件index.js:
import React from 'react';
import { render } from 'react-dom';
render(<h1>JSX2</h1>, window.root);
1、新建一个webpack.config.dll.js,打包react、react-dom
let path = require('path');
let webpack = require('webpack')
module.exports = {
mode: 'development',
entry: {
// 打包react和react-dom
react: ['react', 'react-dom']
},
output: {
filename: '_dll_[name].js', // 打包后的文件名
path: path.resolve(__dirname, 'dist'),
library: '_dll_[name]', // 打包后js接收返回值的变量_dll_react
},
plugins: [
new webpack.DllPlugin({
name: '_dll_[name]', //name值 === output.library
//生成manifest文件输出的位置和文件名称
path: path.resolve(__dirname, 'dist', 'manifest.json')
})
]
}
2、webpack.config.js
let path = require('path');
let HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
module.exports = {
mode: 'development',
entry: {
index: './src/index.js'
}, // 入口
output: { // 出口
filename: '[name].js',
path: path.resolve(__dirname, 'dist'),
},
module: {
plugins: [
new HtmlWebpackPlugin({
template: './index.html',
filename: 'index.html',
title: 'webpack测试'
}),
// 引用dll插件,在打包文件目录里查找是否有manifest.json清单目录,没有就不用重新打包
new webpack.DllReferencePlugin({
manifest: path.resolve(__dirname, 'dist', 'manifest.json')
})
]
}
3、构建代码,打包第三方库文件
npx webpack --config webpack.dll.config.js
生成_dll_react.js和manifest.json文件,然后运行 npm run build打包其它文件,在index.html(HtmlWebpackPlugin里的index.html)手动添加_dll_react.js的引入
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div id="root"></div>
<script src="/_dll_react.js"></script>
</body>
</html>
4、运行npm run dev,运行代码