note icon indicating copy to clipboard operation
note copied to clipboard

介绍一下 rollup 插件,以及插件的开发规范?

Open banli17 opened this issue 2 years ago • 3 comments

banli17 avatar Sep 13 '22 14:09 banli17

https://rollupjs.org/guide/en/#plugins-overview

rollup 插件可以让我们自定义 rollup 的行为,它是一个函数,返回一个描述对象,这个对象可以包含:

banli17 avatar Sep 14 '22 15:09 banli17

简单示例

// rollup-plugin-my-example.js
export default function myExample () {
  return {
    name: 'my-example', // this name will show up in warnings and errors
    resolveId ( source ) {
      if (source === 'virtual-module') {
        return source; // this signals that rollup should not ask other plugins or check the file system to find this id
      }
      return null; // other ids should be handled as usually
    },
    load ( id ) {
      if (id === 'virtual-module') {
        return 'export default "This is virtual!"'; // the source code for "virtual-module"
      }
      return null; // other ids should be handled as usually
    }
  };
}

// rollup.config.js
import myExample from './rollup-plugin-my-example.js';
export default ({
  input: 'virtual-module', // resolved by our plugin
  plugins: [myExample()],
  output: [{
    file: 'bundle.js',
    format: 'es'
  }]
});

banli17 avatar Sep 14 '22 15:09 banli17

插件的开发规范,7条

  • 插件名前缀 rollup-plugin- prefix.
  • package.json 包含关键字 rollup-plugin
  • 插件需要被测试,推荐 mochaava 支持 Promises
  • 使用异步方法, e.g. fs.readFile instead of fs.readFileSync.
  • 英文书写文档
  • 如果适合 if appropriate,确保输出正确的 sourcemap
  • 如果插件用了虚拟模块,在模块 ID 前加 \0, 可以防止其它插件处理它。

banli17 avatar Sep 14 '22 15:09 banli17