Skip to content

编写一个去除代码中所有 console.log 的 rollup 插件

写插件

编写 Rollup 插件需要遵循一定的规范。一个 Rollup 插件应该是一个返回一个对象的函数,该对象包含至少一个名为 name 的属性和一个名为 transform 的方法。

name 属性是插件的名称,transform 方法用于处理输入文件,并返回一个转换后的文件对象。

js
// 可以使用命名导出或默认导出
export const removeConsolePlugin = () => {
  return {
    // 插件的名称
    name: 'removeConsolePlugin', 
    // 处理输入文件,并返回一个转换后的文件对象
    /**
      code:要进行转换的代码字符串。
      id:一个文件路径。
     */
    // 如果返回 null 或 undefined,那么这个钩子相当于没有
    transform: (code, id) => { 
      console.log(code, id, 'tranform');
      const str = code.replace(/console\.log\((.*?)\);?/g, '')
      return str
    },
    // 先于 transform 钩子执行
    load: (id) => {
      console.log(id,'load');
      // 如果不为 null,返回内容将作为 transform 钩子的参数 code 值
      // 否则返回源代码字符串
      return null // 返回源代码字符串
    }
  }
}

使用插件

js
import {removeConsolePlugin} from './removeConsolePlugin/index.js'

export default {
  input: "main.js",
  plugins: [
    removeConsolePlugin()
  ],
  output: [
    {
      file: "dist/index.esm.js",
      format: "es", // es 模块化。在第三方支持 es 模块化导出的构建工具中,我们可能需要用到模块化导出。
      name: "test"
    },
  ]
}

transform 钩子类型

ts
(code: string, id: string) => TransformResult;
ts
type TransformResult = string | null | Partial<SourceDescription>;

interface SourceDescription {
	code: string;
	map?: string | SourceMap;
	ast?: ESTree.Program;
	assertions?: { [key: string]: string } | null;
	meta?: { [plugin: string]: any } | null;
	moduleSideEffects?: boolean | 'no-treeshake' | null;
	syntheticNamedExports?: boolean | string | null;
}

Released under the MIT License.