How to remove @license comments from source during npm build (will add manually)?
Asked Answered
L

2

5

I am developing a Vite-React webapp to be used by me only, and heres my simple build command in package.json: "build": "vite build --emptyOutDir --base=./".

It uses the Google Firebase libraries that contains several submodules wherein each has the exact same @license comment leading to 48 times the same repeated text contributing to 80% of my build since everything else I have gzipped anyway. Now I have no issue with manually, thankfully, and carefully adding all unique licenses wherever appropriate, but at first I wish to remove licenses during the build.

I realize the "@license" is probably the marker the minifier looks for, and I searched around but could not find a way to turn it off. Please advise. And Thanks!

Lani answered 25/9, 2023 at 14:38 Comment(2)
Strip comments in your build? I don't know why anyone would need comments in the build since it's all minified and/or obfuscated. Source maps don't have to be inline either.Guenon
@kelsny exactly! and still license comments do exist in the build if the build tool finds a comment prefixed with "@license" and thereafter skips such comments from minification, Its not obfuscated, and I just wish to remove the duplicates, thats all.Lani
S
13

The default minifier now is esbuild (https://vitejs.dev/config/build-options.html#build-minify).

Here is the new config that works:

export default defineConfig({
  // ...
  build: {
    // ...
  },
  esbuild: { legalComments: 'none' },
})

https://esbuild.github.io/api/#legal-comments

Selector answered 9/10, 2023 at 8:31 Comment(0)
D
4

You need to configure terser through your vite.config.js:

export default defineConfig({
  build: {
    terserOptions: {
      format: {
        comments: false
      }
    }
  }
});

comments (default "some") -- by default it keeps JSDoc-style comments that contain "@license", "@copyright", "@preserve" or start with !, pass true or "all" to preserve all comments, false to omit comments in the output, a regular expression string (e.g. /^!/) or a function.

Terser's Docs

Dov answered 25/9, 2023 at 18:19 Comment(4)
Thanks you pointed me in the right direction. During build I found that Terser is no longer default build tool, and so I will have to configure esbuild instead.Lani
So I didnt find any esbuild config options that Vite exposes in its settings, nor any other easy way, and also Terser is listed to be a better minifier, so I installed that. thxLani
Does this still work? My comments are not removed. In fact nearly all options are totally ignored. I made sure to add minify: 'terser'Oleaceous
@RobinSchambach It looks like Vite ignores (for reasons) terserOptions when building ES modules in lib mode, as discussed in github.com/vitejs/vite/issues/5167. A workaround is the @rollup/plugin-terser which forces terser to run anyway.Outfox

© 2022 - 2024 — McMap. All rights reserved.