简体   繁体   中英

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 -->

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.

I know this is an old thread. But if someone else is having this situation you could just use gulp.

Create a file called gulp.js with following content:

const gulp = require("gulp");
const gap = require("gulp-append-prepend");

gulp.task("opensource", function (done) {
  gulp
    .src("build/index.html", { base: "./" })
    .pipe(
      gap.appendText(`<!-- this project is open source -->`)
    )
    .pipe(gulp.dest("./", { overwrite: true }));
  done();
  return;
});

and then you can use

"build": "react-scripts build && gulp opensource",

in your package.json

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM