javascriptwebpackwebpack-4

How to create multi output files?


I would like to bundle my chrome extension with Webpack. The source consists multiple entries and the content of the webpack.config.js looks as follows:

const path = require("path");

module.exports = {
  entry: {
    actions: './src/actions/index.js',
    options: './src/options/index.js'
  },
  output: {
    filename: '[name].js',
    path: path.resolve(__dirname, "dist")
  }
};

And folder structure:
enter image description here

The actions/index.js and options/index.js files are entries. My goal is, when the src get bundled then dist folder should looks as follows:

enter image description here

How to configure the webpack config to get the desired folder structure above?

Thanks


Solution

  • This should solve your problems ;)

    file structure

    src
    ├── actions
    │   ├── index.html
    │   └── index.js
    └── options
        ├── index.html
        └── index.js
    

    webpack.config.js

    const path = require('path');
    const HtmlWebPackPlugin = require('html-webpack-plugin');
    
    module.exports = {
      entry: {
        actions: './src/actions/index.js',
        options: './src/options/index.js'
      },
      output: {
        path: path.resolve(__dirname, 'dist'),
        filename: '[name]/index.js'
      },
      plugins: [
        new HtmlWebPackPlugin({
          template: './src/actions/index.html',
          filename: 'actions/index.html',
          chunks: ['actions']
        }),
        new HtmlWebPackPlugin({
          template: './src/options/index.html',
          filename: 'options/index.html',
          chunks: ['options']
        })
      ]
    };
    

    And a more correct version ;)

    const path = require('path');
    const HtmlWebPackPlugin = require('html-webpack-plugin');
    
    const ENTRY = {
      actions: './src/actions/index.js',
      options: './src/options/index.js'
    }
    
    const entryHtmlPlugins = Object.keys(ENTRY).map(entryName => {
      return new HtmlWebPackPlugin({
        template: `./src/${entryName}/index.html`,
        filename: `${entryName}/index.html`,
        chunks: [entryName]
      });
    });
    
    module.exports = {
      entry: ENTRY,
      output: {
        path: path.resolve(__dirname, 'dist'),
        filename: '[name]/index.js'
      },
      plugins: entryHtmlPlugins
    };
    

    I created a branch on github many-outputs