combine react build output into single js file

后端 未结 1 724
挽巷
挽巷 2020-12-09 05:58

This is similar to this question however neither of the answers solves the problem.

After running npm run build the resultant index.html lo

相关标签:
1条回答
  • 2020-12-09 06:29

    In short: It's possible, but not practical. Why? Your app will no longer be progressive and your single js file can be very large (slower performance all around with none of the code splitting benefits webpack offers).

    While I'm not a fan of the create-react-app nor bundling everything into one bundle.js file, you'll first want to eject: yarn eject or npm run eject -- you can probably use some 3rd party packages to override without ejecting, but I'll leave that up to you to figure out.

    Then, you'll need to go to the config/webpack.config.js and do the following:

    • Remove InlineChunkHtmlPlugin from required imports and under plugins: , remove isEnvProduction && shouldInlineRuntimeChunk && new InlineChunkHtmlPlugin(HtmlWebpackPlugin, [/runtime-.+[.]js/]) as it creates a chunk file list inside the index.html file when building
    • Under output: , change filename: to filename: "static/js/bundle.min.js",
    • Under output: , remove the chunkFilename: property as you're no longer chunking js files during production
    • Under optimization: , remove splitChunks: property as you're no longer splitting chunks when building
    • Under optimization: , set runtimeChunk: to runtimeChunk: false to avoid creating a runtime-chunk.js file when building
    • Under plugins: , change MiniCssExtractPlugin options to only output a single css file by changing filename to filename: "static/css/bundle.min.css", and removing chunkFileName:.

    Working repo: https://github.com/mattcarlotta/cra-single-bundle

    I also added two package.json start scripts to the repo:

    1.) To test the production build; run yarn prod or npm run prod after compiling your source.

    2.) To analyze a webpack bundle, run yarn analyze or npm run analyze to view a chunk distribution chart.

    0 讨论(0)
提交回复
热议问题