Search code examples
javascriptwebpackextracttextwebpackplugin

Extracting a javascript file from webpack build


I am using webpack for a project where I need to have a javascript config file as part of the built files, but I cannot figure out how to do that.

So I need to have these files in the output:

index.html app.js config.js

I figure I need to either:

1) Copy the config.js file from the source folder to the build folder with CopyWebpackPlugin, or

2) Include the file in the compiled bundle and then extract it with ExtractTextWebpackPlugin.

I have tried dozens of different ways of configuring this, but when trying with the copy method, I get the file both inside the app.js bundle AND as a separate file. When I try with the extract method, I cannot seem to figure out how to extract javascript from the main bundle. The docs all seem to explain how to extract css.

How would I go about something like this?


Solution

  • You should be able to accomplish this by using multiple entry points. https://webpack.js.org/concepts/entry-points/

    entry: {
        main: './path/to/file/app.js',
        config: './path/to/file/config.js'
    }
    
    output: {
        filename: 'output/path/[name].js'
    }
    

    A more complex option, which is typically used for vendor files, would be to use code-splitting. https://webpack.js.org/guides/code-splitting/