Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In webpack, how can I have different output directories for multiple entry points?

I have the following webpack configuration with multiple entry points...

module.exports = {
 entry: {
  somePage: "./scripts/someDir/somePage.js",
  anotherPage: "./scripts/someDir/someSubDir/anotherPage.js"
 },
 output: {
   path: path.resolve(__dirname, 'out'),
   filename: '[name].js'
 },
 ...

Is it possible to set a different output path for each entry?

Instead of getting an output of...

/out/somePage.js /out/anotherPage.js

I want...

/out/someDir/somePage.js /out/someDir/someSubDir/anotherPage.js

The ideal solution for me would be for output.path to accept a function. For example...

...
output: {
   path: function (name, hash) {
       return path.resolve(__dirname, myMapOfFilenamesToDirs[name]);
   },
   filename: '[name].js'
},

Does anyone know if this is possible or if there is an existing plugin that can accomplish this?

EDIT I don't want to use multiple config entries (multi-compiler) because I won't be able to create a shared file among the entry points with CommonsChunkPlugin anymore

like image 997
Charlie Martin Avatar asked Oct 09 '15 16:10

Charlie Martin


People also ask

How do you get multiple entry points on webpack?

webpack.config.js module. exports = { entry: { main: './path/to/my/entry/file. js', }, }; We can also pass an array of file paths to the entry property which creates what is known as a "multi-main entry".

What is __ Dirname in webpack?

__dirname returns the the directory name of the current module. Let's take a look at some code that uses __dirname . Without webpack. This is what the output of it looks like.

What is output in webpack config?

Configuring the output configuration options tells webpack how to write the compiled files to disk. Note that, while there can be multiple entry points, only one output configuration is specified.

What is bundling webpack?

Bundling tools such as Webpack and Browsify organizes and puts all your JavaScript, HTML, CSS, images and everything else in between together in a handful of neat little files to help make your web application run smoothly. These bundling tools comes pre-baked into Angular and React CLIs.


1 Answers

A bit hacky, but this should do the trick.

module.exports = {
 entry: {
  "somePage": "./scripts/someDir/somePage.js",
  "someSubDir/anotherPage": "./scripts/someDir/someSubDir/anotherPage.js"
 },
 output: {
   path: path.resolve(__dirname, 'out/someDir'),
   filename: '[name].js'
 },
 // Etc.
}

You cannot set the path to a function, webpack won't call it for you.

like image 177
Quentin Roy Avatar answered Oct 07 '22 18:10

Quentin Roy