Multiple dynamic write scripts in webpack?

Say I have an application structure like

app/ modules/ module1/ <other files> script.js module2/ <other files> script.js module3/ <other files> script.js lib/ <some common/shared scripts to import from> public/ js/ 

How to configure webpack to combine and output each script.js (which will import various libraries / utilities from the lib shared folder) into such a structure?

eg.

 public/js/module1/script.js public/js/module2/script.js 

But without an individual definition of each recording file? Does something like gulp do with the syntax /**/*.js ?

My goal is not to support my webpack.config.js file every time I add a new module / component.

+6
source share
1 answer

You need the glob package and set the entry and output to webpack.config.js . Example when webpack.config.js in the root directory.

 var webpack = require('webpack'); var glob = require('glob'); //Generate object for webpack entry //rename './app/modules/module1/script.js' -> 'module1/script' var entryObject = glob.sync('./app/modules/**/script.js').reduce( function (entries, entry) { var matchForRename = /^\.\/app\/modules\/([\w\d_]+\/script)\.js$/g.exec(entry); if (matchForRename !== null && typeof matchForRename[1] !== 'undefined') { entries[matchForRename[1]] = entry; } return entries; }, {} ); module.exports = { ... entry: entryObject,//{'moduleName/script': './app/modules/moduleName/script.js', ...} output: { path: __dirname + '/public/js', filename: '[name].js'//'moduleName/script.js', [name] - key from entryObject } ... }; 

If you have an error with fs, for example, "cannot resolve" fs "add"

 node: { fs: "empty" } 

Alternatively, you can link your files to <other files> in a public script.js using another entryObject.

 var entryObject = glob.sync('./app/modules/**/*.js').reduce( function (entries, entry) { var matchForRename = /^\.\/app\/modules\/([\w\d_]+)\/.+\.js$/g.exec(entry); if (matchForRename !== null && typeof matchForRename[1] !== 'undefined') { var entryName = matchForRename[1] + '/script'; if (typeof entries[entryName] !== 'undefined') { entries[entryName].push(entry); } else { entries[entryName] = [entry]; } } return entries; }, {} ); 
0
source

All Articles