react项目将原来的单页面应用改成分模块打包
webpack中entry由单入口改成多入口,由于模块较多,个数不固定因此在webpack中写死入口不可取。采用动态获取打包入口的方法,在根目录下新建config文件夹,获取每个打包入口文件路径:新建get-path.js
module.exports = function getPath(path){
let arr = [];
let existpath = fs.existsSync(path); //是否存在目录
if(existpath){
let readdirSync = fs.readdirSync(path); //获取目录下所有文件
readdirSync.map((item)=>{
let currentPath = path + "/" + item;
let isDirector = fs.statSync(currentPath).isDirectory(); //判断是不是一个文件夹
if(isDirector){ // component目录下为组件 需要排除
arr.push(item);
}
});
return arr;
}
};
获取入口文件:新建,get-entry.js,将每个模块目录下的index.js作为打包入口文件
const getPath = require("./get-path");
module.exports = function getEnty(path){
let entry = {};
getPath(path).map((item)=>{
entry[`${item}/${item}`] = `${path}/${item}/index.js`;
});
return entry;
};
将webpack.base.conf.js中的entry换成动态生成的入口文件
const getEntry = require("./config/get-entry");
const entry = getEntry("./src/pages");
module.exports = {
entry: entry,
...
}
entry配置好之后,需要将每个入口生成index.html文件,默认的webpack主要是用于处理js文件的依赖图构建和打包,当需要生成html文件时,便需要使HtmlWebpackPlugin插件,同样也需要动态生成,在config目录下新建create-html.js
const fs = require("fs");
const HtmlWebpackPlugin = require("html-webpack-plugin");//生成html文件
const getPath = require("./get-path");
let htmlArr = [];
function createHtml(page_path){
getPath(page_path).map((item)=>{
let infoJson ={},infoData={};
try{
// 读取pageinfo.json文件内容,如果在页面目录下没有找到pageinfo.json 捕获异常
infoJson = fs.readFileSync(`${page_path}/${item}/pageinfo.json`,"utf-8");//
infoData = JSON.parse(infoJson);
}catch(err){
infoData = {};
}
htmlArr.push(new HtmlWebpackPlugin({
// title:infoData.title ? infoData.title : "webpack,react多页面架构",
chunks:[`${item}/${item}`], //引入的js
template: "./src/template.html",
filename : item == "index" ? "index.html" : `${item}/index.html`, //html位置
minify:{//压缩html
collapseWhitespace: true,
preserveLineBreaks: true
},
}));
});
return htmlArr;
}
module.exports = createHtml;
webpack.base.conf.js
module.exports = {
plugins: [
...htmlArr, // html插件数组
]
}
现在多页面打包已经完成,要想实现多模块打包,每个入口文件中模块目录结构是这样的
入口文件index.js
import '../../common/businessUtils/antm-viewport.min';
// import './assets/css/base.less';
import '../../assets/css/reset.css';
import '../../assets/css/index.scss'
import React from 'react';
import { render } from 'react-dom';
import { HashRouter,hashHistory} from 'react-router-dom';
import CacheRoute, { CacheSwitch } from 'react-router-cache-route'
import { Provider } from 'react-redux';
import Router from './router';
import 'src/common/jsNativeInteraction/mobile_agent_plugin'
render(
<HashRouter forceRefresh={false}>
<CacheSwitch>
{
Router.map((item,key)=>{
if(item.show){
return (<CacheRoute exact key={key} path={item.path} history={hashHistory} component={item.component}></CacheRoute>)
}
})
}
</CacheSwitch>
</HashRouter>
,
document.getElementById("root")
);
入口文件基本和之前的main.js 没什么变化,采用hashRouter将router.js中的路由对应页面渲染出来,这样既实现了分模块打包,每个模块中路由跳转依然能使用每个模块大小基本上都在800K一下
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。