[英]How to load all files in a directory using webpack without require statements
I have a large amount of javascript files split into 4 subdirectory in my app.我在我的应用程序中有大量的 javascript 文件分成 4 个子目录。 In grunt I grab all of them and compile them into one file.
在 grunt 中,我抓取所有这些并将它们编译成一个文件。 These files do not have a module.exports function.
这些文件没有 module.exports 函数。
I want to use webpack and split it into 4 parts.我想使用 webpack 并将其分成 4 部分。 I don't want to manually go in and require all my files.
我不想手动进入并需要我的所有文件。
I would like to create a plugin that on compilation walks the directory trees, then grabs all the .js file names and paths, then requires all files in the sub directories and adds it to the output.我想创建一个插件,在编译时遍历目录树,然后获取所有 .js 文件名和路径,然后需要子目录中的所有文件并将其添加到输出中。
I want all the files in each directories compiled into a module that I could then require from my entry point file, or include in the assets that http://webpack.github.io/docs/plugins.html mentions.我希望将每个目录中的所有文件编译成一个模块,然后我可以从我的入口点文件中要求该模块,或者包含在http://webpack.github.io/docs/plugins.html提到的资产中。
When adding a new file I just want to drop it in the correct directory and know it will be included.添加新文件时,我只想将其放入正确的目录中并知道它将被包含在内。
Is there a way to do this with webpack or a plugin that someone has written to do this?有没有办法用 webpack 或某人编写的插件来做到这一点?
This is what I did to achieve this:这就是我为实现这一目标所做的:
function requireAll(r) { r.keys().forEach(r); }
requireAll(require.context('./modules/', true, /\.js$/));
In my app file I ended up putting the require在我的应用程序文件中,我最终放置了要求
require.context(
"./common", // context folder
true, // include subdirectories
/.*/ // RegExp
)("./" + expr + "")
courtesy of this post: https://github.com/webpack/webpack/issues/118这篇文章的礼貌: https : //github.com/webpack/webpack/issues/118
It is now adding all my files.它现在正在添加我的所有文件。 I have a loader for html and css and it seems to work great.
我有一个 html 和 css 加载器,它似乎工作得很好。
How about a map of all the files in a folder?一个文件夹中所有文件的映射怎么样?
// {
// './image1.png': 'data:image/png;base64,iVBORw0KGgoAAAANS',
// './image2.png': 'data:image/png;base64,iVBP7aCASUUASf892',
// }
Do this:做这个:
const allFiles = (ctx => {
let keys = ctx.keys();
let values = keys.map(ctx);
return keys.reduce((o, k, i) => { o[k] = values[i]; return o; }, {});
})(require.context('./path/to/folder', true, /.*/));
Example of how to get a map of all images in the current folder.如何获取当前文件夹中所有图像的地图的示例。
const IMAGES_REGEX = /\.(png|gif|ico|jpg|jpeg)$/;
function mapFiles(context) {
const keys = context.keys();
const values = keys.map(context);
return keys.reduce((accumulator, key, index) => ({
...accumulator,
[key]: values[index],
}), {});
}
const allImages = mapFiles(require.context('./', true, IMAGES_REGEX));
All merits to @splintor (thanks). @splintor 的所有优点(谢谢)。
But here it is my own derived version.但这里是我自己的派生版本。
Benefits:好处:
{module_name: exports_obj}
object.{module_name: exports_obj}
对象下。
EDIT: If, like me, you're sure your modules won't return anything else than (at least at root level) a regular javascript object, you can also "mount" them replicating their original directory structure (see Code (Deep Version) section at the end).
编辑:如果像我一样,你确定你的模块除了(至少在根级别)一个常规的 javascript 对象之外不会返回任何东西,你也可以“挂载”它们复制它们的原始目录结构(参见代码(深度版本) )部分)。
Code (Original Version):代码(原版):
function requireAll(r) {
return Object.fromEntries(
r.keys().map(function(mpath, ...args) {
const result = r(mpath, ...args);
const name = mpath
.replace(/(?:^[.\/]*\/|\.[^.]+$)/g, '') // Trim
.replace(/\//g, '_') // Relace '/'s by '_'s
;
return [name, result];
})
);
};
const allModules = requireAll(require.context(
// Any kind of variables cannot be used here
'@models' // (Webpack based) path
, true // Use subdirectories
, /\.js$/ // File name pattern
));
Example:例子:
Sample output for eventual console.log(allModules);
最终
console.log(allModules);
示例输出console.log(allModules);
: :
{
main: { title: 'Webpack Express Playground' },
views_home: {
greeting: 'Welcome to Something!!',
title: 'Webpack Express Playground'
}
}
Directory tree:目录树:
models
├── main.js
└── views
└── home.js
Code (Deep Version):代码(深度版):
function jsonSet(target, path, value) {
let current = target;
path = [...path]; // Detach
const item = path.pop();
path.forEach(function(key) {
(current[key] || (current[key] = {}));
current = current[key];
});
current[item] = value;
return target;
};
function requireAll(r) {
const gather = {};
r.keys().forEach(function(mpath, ...args) {
const result = r(mpath, ...args);
const path = mpath
.replace(/(?:^[.\/]*\/|\.[^.]+$)/g, '') // Trim
.split('/')
;
jsonSet(gather, path, result);
});
return gather;
};
const models = requireAll(require.context(
// Any kind of variables cannot be used here
'@models' // (Webpack based) path
, true // Use subdirectories
, /\.js$/ // File name pattern
));
Example:例子:
Result of previous example using this version:使用此版本的先前示例的结果:
{
main: { title: 'Webpack Express Playground' },
views: {
home: {
greeting: 'Welcome to Something!!',
title: 'Webpack Express Playground'
}
}
}
this works for me :这对我有用:
function requireAll(r) { r.keys().forEach(r); }
requireAll(require.context('./js/', true, /\.js$/));
NOTE: this can require .js files in subdirs of ./js/ recursively.注意:这可能需要 ./js/ 子目录中的 .js 文件递归。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.