0

I have written a React app that has a standalone version and an embedded version. The difference is that the embedded version misses afew components and that it does a lot of lazy loading (it is heavily reduced in size versus the standalone version). Because of the lazy loading the embedded version generates a lot of js files. Now what I'm trying to achieve is that whenever I build my project(s) that it creates two folders;

  • build/standalone => all JS files needed to import the standalone application into any html project
  • build/embedded => all JS files needed to import the embedded application into any html project

How could I do this?

webpack.common.js

module.exports = {
    entry: {
        standalone: path.resolve(__dirname, '../src/index.standalone.tsx'),
        embedded: path.resolve(__dirname, '../src/index.embedded.tsx')
    },
    resolve: {
        extensions: ['.tsx', '.ts', '.js']
    },
    output: {
        path: path.resolve(__dirname, '..', './build'),
        filename: '[name].[contenthash].bundle.js' // I know I could do ./[name]/[contenthash].bundle.js but this also results in folders for chunks
    },
    optimization: {
        runtimeChunk: 'single',
        splitChunks: {
            chunks: 'all'
        }
    },
    plugins: [
        new HtmlWebpackPlugin({
            template: path.resolve(__dirname, '..', './public/index.html')
        })
    ]
};

What I get right now, which is not what I want;

enter image description here

With this its nearly impossible to know what files you need to, for example, implement the embedded version on my webpage.

Martijn Ebbens
  • 514
  • 2
  • 5
  • 14

1 Answers1

0

One straightforward way to achieve this is to make output.filename a function and use the chunk name.

output: {
  path: path.resolve(__dirname, '..', './build'),
  filename: (pathData) => {
    return `${pathData.chunk.name}/[name].[contenthash].bundle.js`;
  },
},

There are more examples in the linked docs.

Etheryte
  • 24,589
  • 11
  • 71
  • 116
  • This doesn't work with splitChunks, I get these folders; `embedded`, `runtime`, `standalone`, `undefined` and then each has a js file in it. For example `191.js` should also be in the `embedded` and `runtime` folder as both of these need `191.js` to run. – Martijn Ebbens Jun 15 '22 at 14:44