ChatGPT解决这个技术问题 Extra ChatGPT

How to create multiple output paths in Webpack config

Does anyone know how to create multiple output paths in a webpack.config.js file? I'm using bootstrap-sass which comes with a few different font files, etc. For webpack to process these i've included file-loader which is working correctly, however the files it outputs are being saved to the output path i specified for the rest of my files:

    output: {
      path: __dirname + "/js",
      filename: "scripts.min.js"
    }

I'd like to achieve something where I can maybe look at the extension types for whatever webpack is outputting and for things ending in .woff .eot, etc, have them diverted to a different output path. Is this possible?

I did a little googling and came across this *issue on github where a couple of solutions are offered, edit:

but it looks as if you need to know the entry point in able to specify an output using the hash method eg:

var entryPointsPathPrefix = './src/javascripts/pages';
var WebpackConfig = {
  entry : {
    a: entryPointsPathPrefix + '/a.jsx',
    b: entryPointsPathPrefix + '/b.jsx',
    c: entryPointsPathPrefix + '/c.jsx',
    d: entryPointsPathPrefix + '/d.jsx'
  },

  // send to distribution
  output: {
    path: './dist/js',
    filename: '[name].js'
  }
}

*https://github.com/webpack/webpack/issues/1189

however in my case, as far as the font files are concerned, the input process is kind of abstracted away and all i know is the output. in the case of my other files undergoing transformations, there's a known point where i'm requiring them in to be then handled by my loaders. if there was a way of finding out where this step was happening, i could then use the hash method to customize output paths, but i don't know where these files are being required in.


G
GijsjanB

Webpack does support multiple output paths.

Set the output paths as the entry key. And use the name as output template.

webpack config:

entry: {
    'module/a/index': 'module/a/index.js',
    'module/b/index': 'module/b/index.js',
},
output: {
    path: path.resolve(__dirname, 'dist'),
    filename: '[name].js'
}

generated:

└── module
    ├── a
    │   └── index.js
    └── b
        └── index.js

In my case I want one output to not contain chunkhash, is there any simple solution to that? Thanks.
@zhengkenghong I believe that the generated output path would need dist in it. So instead of module/a/index.js being an output path, it should be module/a/dist/index.js Or else, you are overriding your entry files.
@Sung dist folder is already configured in output path. So the generated file would actually be dist/module/a/index.js, which i didn't mention.
I think this should be the accepted answer as it is the answer from the webpack 4 docs. -> webpack.js.org/concepts/output/#multiple-entry-points
@raRaRa Late to the party, but you can do that by using a function for output.filename as documented here: webpack.js.org/configuration/output/#outputfilename
Y
Yeo

I'm not sure if we have the same problem since webpack only support one output per configuration as of Jun 2016. I guess you already seen the issue on Github.

But I separate the output path by using the multi-compiler. (i.e. separating the configuration object of webpack.config.js).

var config = {
    // TODO: Add common Configuration
    module: {},
};

var fooConfig = Object.assign({}, config, {
    name: "a",
    entry: "./a/app",
    output: {
       path: "./a",
       filename: "bundle.js"
    },
});
var barConfig = Object.assign({}, config,{
    name: "b",
    entry: "./b/app",
    output: {
       path: "./b",
       filename: "bundle.js"
    },
});

// Return Array of Configurations
module.exports = [
    fooConfig, barConfig,       
];

If you have common configuration among them, you could use the extend library or Object.assign in ES6 or {...} spread operator in ES7.


I didn't run the snippet, some error or typo may occur
I did run your snippet, works like charm... Surprised no one spotted this, eh frontend developers, no patience, always in hurry ;-). I export configs the same way, but my declaration is different/standard: var config = { entry: SOURCE_DIR + '/index.jsx', .... } Did not use any multi compiler as well :-\
Or you can just do a webpack && cp etc in npm?
That's very useful for me to deploy an npm package both in the original folder (automatic tests are there) but also in the folder of the app that implements the package. In this way I can skip the npm download step and live test my updated package code until the new version is stable and ready to be published on npm.
<pre><code> var config = { // TODO: Add common Configuration module: {}, }; </code></pre> The module{} object is incorrect. It's not required. It will be extended/merged at the same level as keywords name, entry, output (from your example). <pre><code> { module: { mode: "development", devtool: "source-map" } }, name: "a", entry: "./a/app", output: { path: "/a", filename: "bundle.js" } } </code></pre>
R
Ryan Waldon

You can now (as of Webpack v5.0.0) specify a unique output path for each entry using the new "descriptor" syntax (https://webpack.js.org/configuration/entry-context/#entry-descriptor) –

module.exports = {
  entry: {
    home: { import: './home.js', filename: 'unique/path/1/[name][ext]' },
    about: { import: './about.js', filename: 'unique/path/2/[name][ext]' }
  }
};

Note that webpack 5.0 is still in beta currently
after so many searches, finally found something useful !!
@bryanph Not anymore.
Should be the accepted answer from now on.
Thank you so much, really a very useful answer. Though for some reason the [ext] does not work and I have to add the file extension manually otherwise the [ext] will be concatenated to the name of the file so: about: { import: './about.js', filename: 'unique/path/2/[name][ext]' } will end up about[ext]. Does anyone have this problem or have a reason for this please?
c
cmswalker

If you can live with multiple output paths having the same level of depth and folder structure there is a way to do this in webpack 2 (have yet to test with webpack 1.x)

Basically you don't follow the doc rules and you provide a path for the filename.

module.exports = {
    entry: {
      foo: 'foo.js',
      bar: 'bar.js'
    },

    output: {
      path: path.join(__dirname, 'components'),
      filename: '[name]/dist/[name].bundle.js', // Hacky way to force webpack   to have multiple output folders vs multiple files per one path
    }
};

That will take this folder structure

/-
  foo.js
  bar.js

And turn it into

/-
  foo.js
  bar.js
  components/foo/dist/foo.js
  components/bar/dist/bar.js

@ccnixon it is documented here webpack.js.org/configuration/output/#outputfilename seach for "still allowed".
a
ajobi

If it's not obvious after all the answers you can also output to a completely different directories (for example a directory outside your standard dist folder). You can do that by using your root as a path (because you only have one path) and by moving the full "directory part" of your path to the entry option (because you can have multiple entries):

entry: {
  'dist/main': './src/index.js',
  'docs/main': './src/index.js'
},
output: {
  filename: '[name].js',
  path: path.resolve(__dirname, './'),
}

This config results in the ./dist/main.js and ./docs/main.js being created.


A
Alexander Korostin

You definitely can return array of configurations from your webpack.config file. But it's not an optimal solution if you just want a copy of artifacts to be in the folder of your project's documentation, since it makes webpack build your code twice doubling the overall time to build.

In this case I'd recommend to use the FileManagerWebpackPlugin plugin instead:

const FileManagerPlugin = require('filemanager-webpack-plugin');
// ...
plugins: [
    // ...
    new FileManagerPlugin({
      onEnd: {
        copy: [{
          source: './dist/*.*',
          destination: './public/',
        }],
      },
    }),
],

R
RCRalph

Please don't use any workaround because it will impact build performance.

Webpack File Manager Plugin

Easy to install copy this tag on top of the webpack.config.js

const FileManagerPlugin = require('filemanager-webpack-plugin');

Install

npm install filemanager-webpack-plugin --save-dev

Add the plugin

module.exports = {
    plugins: [
        new FileManagerPlugin({
            onEnd: {
                copy: [
                    {source: 'www', destination: './vinod test 1/'},
                    {source: 'www', destination: './vinod testing 2/'},
                    {source: 'www', destination: './vinod testing 3/'},
                ],
            },
        }),
    ],
};

Screenshot

https://i.stack.imgur.com/KoV5F.png


should be events.onEnd.copy
G
Guillermo F. Lopez

In my case I had this scenario

const config = {
    entry: {
    moduleA: './modules/moduleA/index.js',
    moduleB: './modules/moduleB/index.js',
    moduleC: './modules/moduleB/v1/index.js',
    moduleC: './modules/moduleB/v2/index.js',
  },
}

And I solve it like this (webpack4)

const config = {
entry: {
        moduleA: './modules/moduleA/index.js',
        moduleB: './modules/moduleB/index.js',
        'moduleC/v1/moduleC': './modules/moduleB/v1/index.js',
        'moduleC/v2/MoculeC': './modules/moduleB/v2/index.js',
      },
    }

Thanks, it worked like a charm, and it was by far the easiest solution. Three days earlier and I would have struggle a lot more ;)
this should be the accepted answer now. Easy and with no external tools.
C
Community

You can only have one output path.

from the docs https://github.com/webpack/docs/wiki/configuration#output

Options affecting the output of the compilation. output options tell Webpack how to write the compiled files to disk. Note, that while there can be multiple entry points, only one output configuration is specified. If you use any hashing ([hash] or [chunkhash]) make sure to have a consistent ordering of modules. Use the OccurenceOrderPlugin or recordsPath.


thanks. i'm gonna leave the Q just in case someone might be able to come up with a workaround.
what's your use case for requiring 2 output paths? It sounds like you want 2 applications or 1 application and 1 module.
i thought i needed one that was dedicated to the output generated by the file-loader which was all going into the root of the project whereas I wanted it in its own folder. i wound up just redirecting the output path in the loader itself per my answer below.
This isn't completely true. You can technically only specify one output path but it will apply for each key in an entry object, allowing you to have multiple outputs -- webpack.js.org/concepts/entry-points
s
sanjsanj

I wrote a plugin that can hopefully do what you want, you can specify known or unknown entry points (using glob) and specify exact outputs or dynamically generate them using the entry file path and name. https://www.npmjs.com/package/webpack-entry-plus


s
spb

I actually wound up just going into index.js in the file-loader module and changing where the contents were emitted to. This is probably not the optimal solution, but until there's some other way, this is fine since I know exactly what's being handled by this loader, which is just fonts.

//index.js
var loaderUtils = require("loader-utils");
module.exports = function(content) {
    this.cacheable && this.cacheable();
    if(!this.emitFile) throw new Error("emitFile is required from module system");
    var query = loaderUtils.parseQuery(this.query);
    var url = loaderUtils.interpolateName(this, query.name || "[hash].[ext]", {
        context: query.context || this.options.context,
        content: content,
        regExp: query.regExp
    });
    this.emitFile("fonts/"+ url, content);//changed path to emit contents to "fonts" folder rather than project root
    return "module.exports = __webpack_public_path__ + " + JSON.stringify( url) + ";";
}
module.exports.raw = true;

Don't know if this is still an issue for you but have a look at npmjs.com/package/webpack-entry-plus
f
fariborz shalghooni por

u can do lik

var config = {
    // TODO: Add common Configuration
    module: {},
};

var x= Object.assign({}, config, {
    name: "x",
    entry: "./public/x/js/x.js",
    output: {
       path: __dirname+"/public/x/jsbuild",
       filename: "xbundle.js"
    },
});
var y= Object.assign({}, config, {
    name: "y",
    entry: "./public/y/js/FBRscript.js",
    output: {
       path: __dirname+"/public/fbr/jsbuild",
       filename: "ybundle.js"
    },
});

let list=[x,y];

for(item of list){
    module.exports =item;
}

Welcome to SO. Please review how to write a good answer. Adding context and explanation will make your answer better.
N
Nimantha

The problem is already in the language:

entry (which is a object (key/value) and is used to define the inputs*)

output (which is a object (key/value) and is used to define outputs*)

The idea to differentiate the output based on limited placeholder like '[name]' defines limitations.

I like the core functionality of webpack, but the usage requires a rewrite with abstract definitions which are based on logic and simplicity... the hardest thing in software-development... logic and simplicity.

All this could be solved by just providing a list of input/output definitions... A LIST INPUT/OUTPUT DEFINITIONS.

Vinod Kumar's good workaround is:

module.exports = {
   plugins: [
    new FileManagerPlugin({
      events: {
        onEnd: {
          copy: [
            {source: 'www', destination: './vinod test 1/'},
            {source: 'www', destination: './vinod testing 2/'},
            {source: 'www', destination: './vinod testing 3/'},
          ],
        },
      }
    }),
  ],
};