Home > database >  "webpack config" - modify assets path of the generated html file
"webpack config" - modify assets path of the generated html file

Time:11-23

When we build the react app using react-scripts build, the relative paths for the created js/css are like: /static/js/main.b8ba68fa.js and so on.

Generated index.html:

<head>
  ...
  <link rel="icon" href="/favicon.ico" />
  <link rel="manifest" href="/manifest.json" />
  <link rel="stylesheet" href="/fonts/fonts.css" />
  <script defer="defer" src="/static/js/main.b8ba68fa.js"></script>
  ...
</head>

What I need index.html:

<head>
  ...
  <link rel="icon" href="{{DOMAIN}}/favicon.ico" />
  <link rel="manifest" href="{{DOMAIN}}/manifest.json" />
  <link rel="stylesheet" href="{{DOMAIN}}/fonts/fonts.css" />
  <script defer="defer" src="{{DOMAIN}}/static/js/main.b8ba68fa.js"></script>
  ...
</head>

What I need is that all the paths of the generated index.html have this string {{DOMAIN}} prepended to them.

CodePudding user response:

You wont be able to modify webpack configuration without ejecting the CRA app. But once you do you'll be able to modify the build output folder for JS and CSS in webpack.

For more info about ejecting https://github.com/facebook/create-react-app/blob/main/packages/cra-template/template/README.md#npm-run-eject

CodePudding user response:

After some trials, I discovered that:
The HtmlWebpackPlugin plugin which generates the index.html file, uses the webpackConfig.output.publicPath (the webpack config object) to prepend to all the paths.

I modified the webpack.config.js to this:

{
  output: {
    ...
    // publicPath: paths.publicUrlOrPath (how it was)
    publicPath: isEnvProduction ? '{{DOMAIN}}' : paths.publicUrlOrPath,  
    ...
  ...
  }
}
  • Related