reactjsminifyuglifyjs

Force new line on minified react build


I'm currently working on an open source project and want to add an extra line that has comment including link of the project on it so if somebody goes to page sources he will see the link, but I have a problem, react will minify the sources on build and deletes all comments on public html, how can I trick react build to not delete my comment and even put newline before it.

my public index.html:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <link rel="icon" href="%PUBLIC_URL%/static/favicon.ico" />
    <title>...</title>
  </head>
  <body>
    <noscript>You need to enable JavaScript to run this app.</noscript>
    <div id="root"></div>
  </body>
</html>
<!-- this project is open source -->

build version:

<!doctype html><html lang="en"><head>.....</html>

what i want:

<!doctype html><html lang="en"><head>.....</html>
<!-- this project is open source -->

Solution

  • I can think of two ways to do this:

    Using Webpack

    There is a webpack plugin that does this. It was, however, written for webpack 4, so it might not work with v5. And it adds the banner to the top of the file, not the end.

    html-webpack-top-banner-plugin

    Appending the banner after build

    You could also simply append to the file after it has been built. (I'm assuming you're using Linux here but a similar approach can be found for other OS'es)

    Modify the build script in package.json like so:

    "build": "react-scripts build && echo '\n<!-- This is open source -->' >> build/index.html",
    

    Next time you run the build, the comment will be appended to the file.