Javascript webpack 需要目录中的每个文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29891458/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 04:15:16  来源:igfitidea点击:

webpack require every file in directory

javascriptwebpack

提问by yonatanmn

This is my file structure

这是我的文件结构

-main.js
-SomeDir
   -fileA.js
   -fileB.js

What should I do if I want to load (inside main.js) every file in someDirwithout specifying the file names -

如果我想main.jssomeDir不指定文件名的情况下加载(内部)每个文件,我该怎么办-

something like: require(./someDir/*.js)?

类似的东西:require(./someDir/*.js)

回答by yonatanmn

Solution:

解决方案:

var req = require.context("../someDir", true, /^(.*\.(js$))[^.]*$/igm);
req.keys().forEach(function(key){
    req(key);
});
// or just: req.keys().forEach(req)

extra:

额外的:

regex to match jsbut ignore test.js

正则表达式匹配js但忽略test.js

/^(?!.*test.js)((.*\.(js\.*))[^.]*$)/igm)

/^(?!.*test.js)((.*\.(js\.*))[^.]*$)/igm)

回答by Tudor Ilisoi

Yes, it is possible, even recursively in the folder hierarchy

是的,它是可能的,甚至在文件夹层次结构中递归

Here's a sample:

这是一个示例:

var context = require.context('./', true, /\.(html)$/);
var files={};

context.keys().forEach((filename)=>{
  console.log(filename);
  files[filename] = context(filename);
});
console.log(files); //you have file contents in the 'files' object, with filenames as keys

And a live demo here (open up devtools to see the generated object)

和一个现场演示(打开 devtools 查看生成的对象)

http://www.webpackbin.com/Vy6AwkWrz

http://www.webpackbin.com/Vy6AwkWrz

In your case the first line would be

在你的情况下,第一行是

var context = require.context('./SomeDir', false, /\.js$/);

Reference: https://webpack.github.io/docs/context.html#require-context

参考:https: //webpack.github.io/docs/context.html#require-context

回答by VyvIT

One approach could be to create an index.js file in SomeDir location and in that file:

一种方法是在 SomeDir 位置和该文件中创建一个 index.js 文件:

var req = require.context('./', true, /\.js$/);
req([]);

Then in main.js:

然后在 main.js 中:

require('./SomeDir');

or

或者

require('./SomeDir/index.js');

or even

甚至

import something from "./SomeDir";