Home  >  Q&A  >  body text

Use webpack to load all files in a directory without requiring a require statement

<p>I have a large number of javascript files scattered across 4 subdirectories of my application. In grunt I collect them all and compile them into one file. There is no module.exports function for these files. </p> <p>I want to split them into 4 parts using webpack. I don't want to reference all the files manually. </p> <p>I want to create a plugin that walks the directory tree at compile time and gets all the .js file names and paths, then references all the files in the subdirectories and adds them to the output. </p> <p>I want all the files in each directory to be compiled into a module which can then be referenced from my entry file or included as mentioned in http://webpack.github.io/docs/plugins.html in resources. </p> <p>When a new file is added, I just want to put it into the correct directory and know it will be included. </p> <p>Is there a way to achieve this using webpack or a plugin written by someone else? </p>
P粉252423906P粉252423906446 days ago446

reply all(2)I'll reply

  • P粉245003607

    P粉2450036072023-08-23 12:36:39

    In my app file I ended up placing require

    require.context(
      "./common", // 上下文文件夹
      true, // 包括子目录
      /.*/ // 正则表达式
    )("./" + expr + "")

    Thanks for this post: https://github.com/webpack/webpack/issues/118

    Now it's adding all my files. I have a loader for html and css that seems to work fine.

    reply
    0
  • P粉351138462

    P粉3511384622023-08-23 09:52:27

    Here's what I did to achieve this:

    function requireAll(r) { r.keys().forEach(r); }
    requireAll(require.context('./modules/', true, /\.js$/));

    reply
    0
  • Cancelreply