随着前端业务的复杂程度不断攀升,项目的体量越来越庞大,文件数量也相应倍增。
当一个大栏目需要手动导入几十上百个模块时,这简直就是噩梦:
import a from './modules/a.js';
import b from './modules/b.js';
import c from './modules/c.js';
import d from './modules/d.js';
import 100+...
const modules = {
a,
b,
c,
d,
100+...
};
卒....
Webpack有个开挂批量导入方法:
require.context()
语法:
require.context(directory, includeSubdirs, filter, mode)
require.context函数接收4个参数:
directory
{String} 读取文件的路径includeSubdirs
{Boolean} 是否遍历文件夹的子目录filter
{RegExp} 过滤文件的正则mode
{String} 加载方式
下面是webpack官方API的介绍:
接下来就可以猛踩油门飙车了:
const files = require.context('./modules', true, /\.js$/); //批量读取模块文件
const modules = files.keys().reduce((modules, path) => {
const name = path.replace(/^\.\/(.*)\.js$/, '$1');
const module = files(path);
modules[name] = module.default;
return modules;
}, {});
* 上面的reduce
是数组的方法,使用方法见:Array.prototype.reduce()