webpack多页面热加载内存溢出

2,321 阅读2分钟

在当时项目刚启动时,我做的第一个页面,那编译速度简直了,秒完成。结果随着业务迁移,越来越多,同时七八个小伙伴在新增页面,后来导致编译时,总是导致内存溢出,崩溃。

既然是内存溢出,首先想到的就是扩大内存,将内存扩大到6个G,

暂时解决,但这并不是长久之计,而且也没从根本上处理,在启动服务和部署代码时,速度极慢。

只编译部分页面

首先我们考虑,如果每次编译时只编译我正在修改的页面,那样速度岂不是要上天!具体实现方案只说下思路,大概是:

  1. 在根目录新建defaultLoad.config.js,保存需编译的pageName集合
  2. 在编译前,从page.config.js中筛选出需编译的page集合
  3. 进行编译,此时会从几十上百个页面中筛选出自己需要的某几个页面。

这种方式的确极大提高了编译速度,但也存在缺点:

每次开发都需要手动修改defaultLoad.config.js,相当于新人文档中将会出现这个配置文件的大名。那肯定有更自动化的方式!

我们知道webpack-dev-server有很多配置项,其中有个before,官网是这么介绍的:

Provides the ability to execute custom middleware prior to all other middleware internally within the server. This could be used to define custom handlers

before(app){
  app.get('/some/path', function(req, res) {
    res.json({ custom: 'response' });
  });
}

利用这个方法,我们可以将 用户将要访问的页面添加的defaultLoad.config.js中。

// pages.config.js
module.exports = {
	activityPage: {
		entry: 'src/pages/activityPage/main.js',
		title: '活动页面',
		chunks: ['chunk-commons', 'chunk-vendors'],
	},
	appPage: {
		entry: 'src/pages/appPage'/main.js,
		title: '端内页面',
		chunks: ['chunk-commons', 'chunk-vendors'],
	},
};
// loadPage.config.js
modules.exports = 'activityPage'; // 不同配置用|分隔
// vue.config.js
const fs = require('fs');
const pages = require('./page.config.js');
const loadPages = {};

let cache = fs.statSync('./defaultLoad.config.js') ? require('./defaultLoad.config.js') : '';

if (cache) {
    const fail = []; // 读不到的路径
    cache.split('|').forEach((name) => {
        const item = pages[name];
        if (fs.existSync(item.entry)) {
            loadPages[name] = pages[name];
        } else {
            fails.push(name);
        }
    });
} else {
    loadPages = pages; // 构建所有页面,所以default中可以写死一个页面
}

module.exports = {
    devServer: {
        before: (app) => {
            app.get('*.html', (req, res, next) => {
                const pageName = req.url.match(/[^/]+?(?=\.|\\)/)[0];
                const pageInfo = pageName && pages[pageName];
                if (pageInfo) {
                    if (!loadPages[pageName]) {
                        fs.writeFileSync('./defaultLoad.config.js', `module.exports="${cache}|${pageName}"`);
                    }
                } else {
                    res.writeHead(200, {'content-type': 'text-html;charset=utf-8'});
                    res.end('不存在的入口');
                }
                next();
            });
            Mocks(app);
        }
    },
};

运行结果:

其他方法

《完美解决webpack多页面热加载缓慢》html-webpack-plugin角度解决问题,同样使用了需要加载页面的配置文件。