webpack4+react多页面架构
webpack在单页面打包上应用广泛,以create-react-app为首的脚手架众多,单页面打包通常是将业务js,css打包到同一个html文件中,整个项目只有一个html文件入口,但也有许多业务需要多个页面不同的入口,比如不同的h5活动,或者需要支持SEO的官方网站,都需要多个不同的html,webpack-react-multi-page架构让你可以实现多页面架构,在项目开发中保证每个页面都可以热更新并且打包后有清晰的文件层次结构。 Github地址项目架构技术使用
目录结构github|-- webpack-react-multi-page //项目 |-- dist //编译生产目录 |-- index |-- index.css |-- index.js |-- about |-- about.css |-- about.js |-- images |-- index.html |-- about.html |-- node_modules //node包 |-- src //开发目录 |-- index //index页面打包入口 |-- images/ |-- app.js// index业务js |-- index.scss |-- index.js //index页面js入口 |-- about //about页面打包入口 |-- images/ |-- app.js// about业务js |-- index.scss |-- index.js //about页面js入口 |-- template.html // html模板 |-- style.scss //公共scss |-- webpackConfig //在webpack中使用 |-- getEntry.js //获取入口 |-- getFilepath.js //遍历文件夹 |-- htmlconfig.js //每个页面html注入数据 |-- package.json |-- .gitignore |-- webpack.config.js //webpack配置文件 |-- www.js //生产启动程序 wikiwebpack单页面打包配置
module.exports = (env,argv) => ({ entry: ".src/index.js",output: { path: path.join(__dirname,"dist"),filename: "bundle.js" },module: { rules: [ ... ],},plugins: [ new HtmlWebpackPlugin({ title: "首页",filename:"index.html",favicon:"",template: "./src/template.html",}) ] }); 这样就可以在 <!DOCTYPE html> <html lang="en"> <head> <title>首页</title> <body> <div id="root"></div> <script type="text/javascript" src="bundle.js"></script> </body> </html> webpack多页面打包配置webpack 的entry支持两种种格式 打包单个文件module.exports = { entry: '.src/file.js',output: { path: path.resolve(__dirname,'dist'),filename: 'bundle.js' } }; 在dist下打包出一个bundle.js 打包出多个文件module.exports = { entry: { index:"./src/index.js",about:"./src/about.js" },filename: '[name].js' } }; 上面在dist下打包出两个与entry属性名对应的index.js,about.js这两个文件 将每个js挂载到相应的html文件上这里我们需要用到 const HtmlWebpackPlugin = require("html-webpack-plugin"); module.exports = (env,argv) => ({ entry: { index:"./src/index.js",filename: '[name].js' } ....//其他配置 plugins: [ new HtmlWebpackPlugin( { filename:"index.html",//生成的index.html template: "./src/template.html",}) //模板 chunks:["index"] }),new HtmlWebpackPlugin( { filename:"about.html",}) //模板 chunks:["about"] }) ] })
上面的配置最终可以在dist下打包出下面的文件结构 |-- dist |-- index.js |-- about.js |-- index.html //内挂载index.js |-- about.html //内挂载about.js 通过上面这样的配置,再加上devServer,我们已经可以实现多页面的配置开发了,但这样很不智能,因为你每增加一个页面,就要在wepback里面配置一次,会非常繁琐,所以我们来优化下,让我们只专注于开发页面,配置交给webpack. wehbpack多页面配置优化我们看下src下面的文件结构 |-- src |-- index |-- app.js |-- index.scss |-- index.js |-- about |-- app.js |-- index.scss |-- index.js src下面每个文件夹对应一个html页面的js业务,如果我们直接把文件夹对应入口js找到并把他们合并生成对应的entry,那是不是就不用手动写entry了呢,再把对应的html-webpack-plugin通过src下目录遍历出来,就可以生成对应的页面。 这样一个完整的多页面架构配置就完成了,完整代码参考项目code 原文地址:https://segmentfault.com/a/1190000016799921 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |