【问题标题】:webpack require every file in directorywebpack 需要目录中的每个文件
【发布时间】:2015-07-05 15:40:44
【问题描述】:

这是我的文件结构

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

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

类似:require(./someDir/*.js) ?

【问题讨论】:

    标签: javascript webpack


    【解决方案1】:

    解决方案:

    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)

    【讨论】:

    • 我在使用这种方法时遇到了错误,有什么建议吗?谢谢。 github.com/webpack/webpack/issues/1635
    • @NickMcCurdy 不是反过来吗? Webpack 1 和 Webpack 2 both support this,但是没有 Webpack 就无法工作……还是我在这里错过了什么?
    • 对不起,我完全错了,这是我不知道的 webpack 语法。删除我的评论。
    • 对此需要什么 ES6 版本?
    • 有谁知道使用这种方法需要多个目录吗?
    【解决方案2】:

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

    这是一个示例:

    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

    【讨论】:

    • 请注意,这些链接已过期
    【解决方案3】:

    一种方法是在 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([]) 行,为什么不起作用?
    • @JianWeihang 好吧,这已经 3 年了,API 发生了变化。如果我没记错的话,它适用于 webpack 1 和 2。
    【解决方案4】:

    Webpack5 导致“webpack-context-dup-keys” Solution here 我们必须在下面使用 /./.*.md$/ 例如

     let ctxWrong   = require.context("../content/posts", true, /\.md$/);
     let ctxCorrect = require.context("../content/posts", true, /\.\/.*\.md$/); 
    

    Please look at issue here

    【讨论】:

      猜你喜欢
      • 2023-03-17
      • 1970-01-01
      • 2015-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-17
      • 2011-05-30
      相关资源
      最近更新 更多