由于公司项目存在多个子业务,前端多业务之间采用的单页应用(为了方便管理,独立发布),我对类似于像我们公司这种业务体系,我考虑整合单页应用(将原来的融合的多个业务剥离开),也算是之前做了一些基础,今天正式开始准备整理目前的基础雏形。
记录一下今天发生的2件BUG修复问题
- 同事的VUE项目中,多个组件的渲染(通过修改多层嵌套的数组长度),其中就发生了一件奇怪的事情
//类似于这样的数组let data = [{b:'四川', zero:[]},{b:'四川', zero:[]},{b:'四川', zero:[]},{b:'四川', zero:[]}]//对这个数组做一个简单的操作:/*** 1. 向倒数第二个元素的位置去新增一个很独立的元素,再次这样就会发生一个很奇怪的子组件的数据渲染问题*///我们向上面一个元素中新增一个空元素,类似于这样data = [{b:'四川', zero:[]},{b:'四川', zero:[]},{b:'四川', zero:[]},{b:'', zero:[]},{b:'四川', zero:[]}]//这些值都会赋值给多个select, 在做了新增元素的操作时,发现页面上倒数第二个新增的数据,还是上一次的倒数第二个值,不曾改变;//这个时候,我就想起了,虚拟dom的底层比较,当索引key相同时,是不会做深层的dom比较,所以,还是显示的上次一个的值//此时我做了一个操作: 将template中的组件循环加了一个唯一key,解决了以上问题;
2.webpack-dev-server中的页面刷新 react-router-dom路由的404的问题
devServer: {contentBase: path.join(__dirname, "src"), //这里标记静态资源的位置,由于项目中会存在引入图片等,需要匹配路径port: 3100,open: true,historyApiFallback: { //由于我是多单页应用的项目,存在多一个index.html输出,此时做了一个映射(可能还需要优化)rewrites: [{ from: /^\/$/, to: '/car/index.html' },{ from: /^\/car/, to: '/car/index.html' },{ from: /^\/train/, to: '/train/index.html' }]}, //历史记录的},
项目大体考虑的结构

- config主要配合页面的文件夹目录等入口管理,打包输出的一系列的出口管理,资源的合并等文件操作
- dist: 主要用于生产项目文件夹
- server:目前打算结合koa做服务器渲染及服务支撑
- src内部主要做: 独立业务的项目管理(这里可能还需要把业务和公用组件文件夹分离)

多个单页应用剥离又通过webpack做监管
开发前的思考
- 由于我之前存在 1.汽车票, 2.火车票, 3. 项目的用户模块,4 .多个其他的业务支撑(比如电子发票业务,火车票抢票业务等),基本上存在融合,由于底层框架是express+easyContoll老路由+jade+light7; 可想而知这个框架已经相当老了,我考虑到先要剥离业务,所以想到一个框架体系,在不改动太多的老代码的前提下,需要做什么?
1) 其一就是独立业务: 以上业务全部采用多个单页应用相互独立
2)采用webpack管理,目前是一个webpack控制多个业务,未来可能会做一些优化(比如项目大需要做开发的优化,打包上传的时候,可以独立部分业务打包不干涉其他业务的生产代码,先考虑这些可能还有很多,现在初步先做一个基本雏形在优化)
- 单页应用的路由情况如何处理(目前,我考虑的是独立路由,可能还有更好的办法,毕竟我比较菜)
webpack.config.js的操作
/** 1. webpack.config.js* 2018.11.25* */const path = require("path");//const MiniCssExtractPlugin = require("mini-css-extract-plugin");//css分离打包const UglifyJsPlugin = require("uglifyjs-webpack-plugin");//js压缩const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin"); //css压缩const HtmlWebpackPlugin = require("html-webpack-plugin");//生成html文件const ExtractTextPlugin = require('extract-text-webpack-plugin');const htmlArr = require("./config/htmlConfig");const getEntry = require("./config/getEntry");let entry = getEntry('./src'); //获取多个子业务的入口module.exports = (env, argv) =>({mode:'production',//配置入口entry: entry,//配置出口output: {path: path.join(__dirname, 'dist'), //out就对应目录输出filename:'[name].[hash:8].js'},module: {rules: [{test: /\.js$/,exclude: /node_modules/,use: {loader:"babel-loader",options:{presets: ["@babel/preset-env", "@babel/preset-react"]}},},{test: /\.css$/,use: ["style-loader", "css-loader"],},{test: /\.(scss|css)$/, //css打包 路径在plugins里use: ExtractTextPlugin.extract({ //css的抽离作为外联引入fallback: "style-loader",use: ['css-loader', 'less-loader','sass-loader']/* { loader: "css-loader", options: { url: false, sourceMap: true } },{ loader: "sass-loader", options: { sourceMap: true } }*/}),},{test: /\.(png|jpg)$/,use:[{loader: "url-loader",options: {name: "./images/[name].[ext]",limit: 8192}}]},],},plugins:[...htmlArr, //这里做了一个htmk的独立渲染,因为这样才可以按业务独立/*new MiniCssExtractPlugin({ //分离css插件filename: "[name].css",chunkFilename: "[id].css"})*/new ExtractTextPlugin({filename:'[name].css',})],devServer: {contentBase: path.join(__dirname, "src"),//设置基本路径,有利于资源的正确引入port: 3100,open: true,historyApiFallback: { //做页面防止刷洗404,单页应用设置成true即可rewrites: [{ from: /^\/$/, to: '/car/index.html' },{ from: /^\/car/, to: '/car/index.html' },{ from: /^\/train/, to: '/train/index.html' }]}, //历史记录的},optimization: {minimizer: [//压缩jsnew UglifyJsPlugin({cache: true,parallel: true,sourceMap: false}),new OptimizeCSSAssetsPlugin({})],splitChunks: { //CommonsChunkPlugin的替代// chunks: 'all', //因为这意味着即使在异步和非异步块之间也可以共享块//压缩csscacheGroups: {styles: {name: "styles",test: /\.css$/,chunks: "all",enforce: true}}}}})/*** /config/getEntry.js*/const getFilePath = require('./getFilePath');//主要是可以所有的entry,配置module.exports = function getEnty(path){let entry = {};getFilePath(path).map((item)=>{entry[`${item}/${item}`] = `${path}/${item}/index.js`});return entry;}//getFilePath.js/*遍历文件目录*/const fs = require("fs");/*** 【遍历某文件下的文件目录】*/module.exports = function getFilePath(path){let arr = [];let existPath = fs.existsSync(path); //是否存在目录if(existPath){let readdirSync = fs.readdirSync(path); //获取目录下的所有文件readdirSync.map((item)=>{let currentPath = path + '/'+item; // path路径下的文件let isDirector = fs.statSync(currentPath).isDirectory(); //判断是不是一个文件夹if(isDirector && item !== 'component'&&item !== 'asset'){// component目录下为组件 需要排除arr.push(item);}})return arr;}}
备注:The CommonsChunkPlugin 已经从 webpack v4 legato 中移除。想要了解在最新版本中如何处理 chunk,请查看 SplitChunksPlugin。(请自行查看)
htmlConfig 页面输出的配置
/*1. htmlConfig 页面输出的配置动态配置html页面,获取src下每个文件下的pageinfo.json内容,解析到HtmlWebpackPlugin中*/const fs = require("path");const HtmlWebpackPlugin = require('html-webpack-plugin') //生成html文件const getFilePath = require("./getFilePath");let htmlArr = [];getFilePath("./src").map((item)=>{let infoJson = {}, infoData = {};try{// 读取pageinfo.json文件内容,如果在页面目录下没有找到pageinfo.json 捕获异常infoJson = fs.readFileSync(`src/${item}/pageinfo.json`,'utf-8'); //得到对象//得到配置infoData = JSON.parse(infoJson); //转化成json格式}catch (e) {infoData = {};}htmlArr.push(new HtmlWebpackPlugin({title:infoData.title ? infoData.title: 'webpack,react多页面架构',meta:{keywords: infoData.keywords ? infoData.keywords : "webpack,react,github",description:infoData.description ? infoData.description : "这是一个webpack,react多页面架构"},chunks:[`${item}/${item}`], //引入的jstemplate:'./src/index.html',filename: `${item}/index.html`,minify:{ //压缩htmlcollapseWhitespace: true,preserveLineBreaks: true}}));})module.exports = htmlArr;
Koa服务(目前是基础服务)
const Koa = require('koa');const app = new Koa();const path = require("path");const serve = require('koa-static'); //静态资源的管理// 1.主页静态网页 把静态页统一放到public中管理// 3.分配路由//console.log("_firName", __dirname);app.use(serve(path.join(__dirname,'../dist/')));/*app.use(async function({method,url, req, res}) {/!*if(method === 'GET'){//这里做一个处理if(url === "/"){//res.redirect(path.resolve(__dirname+"/dist", 'car', 'index.html'))}}*!/ctx.body = 'Hello World';});*/app.listen(3000);
- koa 还需要考虑单页面刷新的问题
- 单页应用的首屏服务端渲染
- 页面接口与后端对接的问题
- koa的http2.0的使用
- 等等,还需要好好思考一下
未完待续….
