使用 rollup 将 TypeScript 构建到 JavaScript 时如何删除注释

问题描述 投票:0回答:3

我正在使用 rollup 来构建我的 TypeScript 源代码。我想仅删除注释,而不进行任何缩小,以便在调试时热更新代码。

我已经尝试过

rollup-plugin-terser
,它可以删除注释,但它也会以某种方式缩小我的代码,我无法完全禁用缩小

我怎样才能做到这一点?谢谢!

javascript typescript webpack rollup
3个回答
11
投票

就像@jubes 在评论中回答的那样,rollup-plugin-cleanup 将完成该任务。我想扩展一点。

三件事:

  • ts
    添加到扩展列表中,如
    extensions: ["js", "ts"]
    — 否则源将不会被处理,即使转译步骤
    typescript()
    在其之前 — 我最初来这里是为了调查为什么
    rollup-plugin-cleanup
    不适用于 TS 文件和只是缺少
    ts
    扩展名 🤦u200d♂️
  • 代码覆盖率很重要;在默认设置下,此插件会删除
    istanbul
    语句,例如
    /* istanbul ignore else */
    ,因此最好排除它们,
    comments: "istanbul",
  • 删除
    console.log
    是一项单独的挑战,由 @rollup/plugin-strip 完成,并且它与
    rollup-plugin-cleanup
    串联。就我而言,根据它是“dev”还是“prod”Rollup 构建(由 CLI 标志
    --dev
    控制,如
    rollup -c --dev
    中所示),我仅在
    console.log
    构建上删除
    prod
    。但是 devprod 版本上的注释都被删除了。

目前,我使用:

import cleanup from "rollup-plugin-cleanup";
...
{
  input: "src/main.ts",
  output: ...,
  external: ...,
  plugins: [
    ...
    cleanup({ comments: "istanbul", extensions: ["js", "ts"] }),
    ...

这是使用我的 Rollup 配置的 示例,这是我的 Rollup 配置

生成器
(在 monorepos 中,Rollup 配置很难手动维护,所以我生成它们)。如果您决定连接 rollup-plugin-cleanup CLI 标志,则问题是您必须在脚本结束之前从
--dev
中删除该标志,否则 Rollup 将抛出异常,请参阅
原始提示
它的实际操作


9
投票
commandLineArgs

实现这一目标。它基于

terser
,因此更多信息实际上可以在其 README 中找到,这是与 minification 相关的部分。所以在你的情况下 rollup-plugin-terser 的这一部分应该看起来像:
rollup.config.js

请记住,您也可以仅为生产启用部分配置。因此,在您的 
plugins: [ terser({ // remove all comments format: { comments: false }, // prevent any compression compress: false }), ],

中声明

production
const 后,您可以这样做:
rollup.config.js



0
投票

package.json:

import { terser } from 'rollup-plugin-terser'; const production = !process.env.ROLLUP_WATCH; export default { plugins: [ production && terser({ // terser plugin config here }), ], };

rollup.config.js:

"devDependencies": { "@rollup/plugin-commonjs": "^22.0.0", "@rollup/plugin-json": "^6.1.0", "@rollup/plugin-terser": "^0.4.4", "rollup": "3.29.5" }

	
© www.soinside.com 2019 - 2024. All rights reserved.