【发布时间】:2015-07-05 15:40:44
【问题描述】:
这是我的文件结构
-main.js
-SomeDir
-fileA.js
-fileB.js
如果我想在不指定文件名的情况下加载(在main.js 内)someDir 中的每个文件,我该怎么办 -
类似:require(./someDir/*.js) ?
【问题讨论】:
标签: javascript webpack
这是我的文件结构
-main.js
-SomeDir
-fileA.js
-fileB.js
如果我想在不指定文件名的情况下加载(在main.js 内)someDir 中的每个文件,我该怎么办 -
类似:require(./someDir/*.js) ?
【问题讨论】:
标签: javascript webpack
var req = require.context("../someDir", true, /^(.*\.(js$))[^.]*$/igm);
req.keys().forEach(function(key){
req(key);
});
// or just: req.keys().forEach(req)
正则表达式匹配js,但忽略test.js
/^(?!.*test.js)((.*\.(js\.*))[^.]*$)/igm)
【讨论】:
是的,有可能,甚至在文件夹层次结构中递归
这是一个示例:
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
还有一个现场演示(打开 devtools 以查看生成的对象)
http://www.webpackbin.com/Vy6AwkWrz
在你的情况下,第一行是
var context = require.context('./SomeDir', false, /\.js$/);
参考:https://webpack.github.io/docs/context.html#require-context
【讨论】:
一种方法是在 SomeDir 位置和该文件中创建一个 index.js 文件:
var req = require.context('./', true, /\.js$/);
req([]);
然后在main.js中:
require('./SomeDir');
或
require('./SomeDir/index.js');
甚至
import something from "./SomeDir";
【讨论】:
req([]) 和在每个键上调用 req 有什么区别,就像接受的答案一样?
Uncaught Error: Cannot find module ''. 在req([]) 行,为什么不起作用?
Webpack5 导致“webpack-context-dup-keys” Solution here 我们必须在下面使用 /./.*.md$/ 例如
let ctxWrong = require.context("../content/posts", true, /\.md$/);
let ctxCorrect = require.context("../content/posts", true, /\.\/.*\.md$/);
【讨论】: