DLL(DynamicLinkLibrary)动态链接库用于webpack中,将共享的和不经常更改的代码提取到公共库中。不使用DLL。React和react-dom是react项目中必备的两个库。提取它们并单独打包。首先安装npminstallreactreact-dom--save在src目录下新建index.jsx文件,编写react代码importReact,{Component}from'react';exportdefaultclassAppextendsComponent{state={message:'helloreact',};render(){返回
{this.state.message}
;}}在第一层的index.js中引入react组件,安装axios后用它发送请求importReactfrom'react';importReactDOMfrom'react-dom';importAppfrom'./app.jsx';从'axios'导入axios;ReactDOM.render(
,document.getElementById('container'));axios.get('https://httpbin.org/get').then((res)=>{console.log('res',res);});react代码需要babel处理,可以参考这篇文章,在不使用DLL的情况下,将第三方库reactreact-dom和axios打包到702.js文件中。如果需要单独打包一些资源,可以使用DLL,新建webpack.dll.js文件,自定义编译规则,通过DllPlugin生成manifest.json文件,其中包含依赖的映射关系。const{DllPlugin}=require('webpack');constpath=require('path');module.exports={entry:{react:['react','react-dom'],},output:{文件名:'./[name].js',path:path.resolve(process.cwd(),'./dll'),library:'[name]',},plugins:[newDllPlugin({name:'[名称]',路径:path.resolve(__dirname,'./dll/manifest.json'),}),],};执行npxwebapck--config./webpack.dll.js后会生成三个文件,mainfest.json、react.js和一个注释文件(可以通过TerserPlugin去除)。如果此时直接编译webpack.config.js文件,react和react-dom还是会作为第三方库和axios一起编译。引入DLL库虽然react和react-dom已经通过DLL自己打包了,但是并没有告诉webpack.config.js不需要打包成公共库。这时,请使用DllReferencePlugin来处理。const{DllReferencePlugin}=require('webpack');module.exports={//其他配置省略plugins:[newDllReferencePlugin({manifest:path.resolve(process.cwd(),'./dll/manifest.json'),上下文:path.resolve(process.cwd(),'./'),}),],};此时第三方库的js文件中没有react和react-dom,文件名也从702.js变成了559.js,因为内容变了。运行编译好的index.html文件,发现报错reactisnotdefined,页面上没有显示helloreact的代码。将文件添加到html中,因为第三库打包的js文件中排除了react和react-dom,而自己打包的react.js没有引入html文件中,所以执行时找不到文件。安装插件add-asset-html-webpack-plugin,使用它导入文件到htmlconstAddAssetHtmlWebpackPlugin=require('add-asset-html-webpack-plugin');module.exports={//其他配置省略插件:[newAddAssetHtmlWebpackPlugin({filepath:path.resolve(process.cwd(),'./dll/react.js'),outputPath:'./auto',}),],};这是DLL编译出来的react。js文件导入到html文件中,页面也可以正常显示了。总结使用DLL自定义打包内容,分为以下三个步骤。使用webpack.dll.js中的DllPlugin生成mainfest.json和js文件。使用webpack.config.js中的DllReferencePlugin查找mainfest.json文件中的映射关系,排除不需要打包的库。在webpack.config.js中,通过add-asset-html-webpack-plugin将资源导入到html文件中以上是使用DLL打包的总结。更多关于webpack的内容可以参考我的其他博文,正在更新中~