简体   繁体   中英

Using webpack to get all paths in directory

I have some front end code which needs to run for each png in a specific directory. I am using Webpack but am unsure of how use it for this.

I realize that Webpack only runs server-side, but that's fine. What I'm looking for is a variable which is an array of paths. I don't want to hard-code it because there are a lot of png files.

Ideally, there is some sort of general-purpose compile time command I can use to interpolate Javascript into the result, something like this:

var glob = require("glob")
var loadFiles = new Promise(funtion(resolve, reject) { 
  CompileTimeCommand(function() {
    glob("assets/tilesheet_images/*.png", function (er, paths) {
      if (err) { reject(err) } else { resolve(paths) }
    })
  })
})
loadFiles.then(function(paths) {
  // etc
})

The problem is, this CompileTimeCommand doesn't exist.

Is there a way I can do this with require , or some sort of general purpose compile-time macro system? I have written a Webpack loader before, but it seems overkill to have to make a new package for a simple, ad-hoc command.

Is there a better way than to just make a separate script which runs the dir glob and saves the paths into a json file which is read by my program?

If you need to get a list of files at run-time and it can change at run-time then you'd rather use your back-end technology to access file system and return results to front-end via http call for example.
Otherwise if files are static and are determined at compile time then you can use glob in webpack config file and put its results into DefinePlugin to replace some variable with a list of files.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM