{"id":26684247,"url":"https://github.com/johnapache/rollup-usage-doc","last_synced_at":"2025-08-22T11:33:30.065Z","repository":{"id":47395584,"uuid":"202119196","full_name":"JohnApache/rollup-usage-doc","owner":"JohnApache","description":"rollup 使用详细教程","archived":false,"fork":false,"pushed_at":"2023-01-04T07:25:57.000Z","size":741,"stargazers_count":17,"open_issues_count":11,"forks_count":5,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-03-26T09:19:22.849Z","etag":null,"topics":["babel","babel7","rollup","rollup-doc","rollup-plugin-babel","rollup-plugin-terser","rollup-plugin-uglify","terser"],"latest_commit_sha":null,"homepage":null,"language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/JohnApache.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2019-08-13T10:19:48.000Z","updated_at":"2022-12-08T15:06:08.000Z","dependencies_parsed_at":"2023-02-02T03:16:23.371Z","dependency_job_id":null,"html_url":"https://github.com/JohnApache/rollup-usage-doc","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JohnApache%2Frollup-usage-doc","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JohnApache%2Frollup-usage-doc/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JohnApache%2Frollup-usage-doc/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/JohnApache%2Frollup-usage-doc/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/JohnApache","download_url":"https://codeload.github.com/JohnApache/rollup-usage-doc/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248583324,"owners_count":21128564,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["babel","babel7","rollup","rollup-doc","rollup-plugin-babel","rollup-plugin-terser","rollup-plugin-uglify","terser"],"created_at":"2025-03-26T09:19:27.588Z","updated_at":"2025-04-12T14:42:36.601Z","avatar_url":"https://github.com/JohnApache.png","language":"JavaScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Rollup 使用教程\n\n## 概述\n引用官方的一句话 \n\u003e Rollup 是一个 JavaScript 模块打包器，可以将小块代码编译成大块复杂的代码，例如 library 或应用程序。Rollup 对代码模块使用新的标准化格式，这些标准都包含在 JavaScript 的 ES6 版本中，而不是以前的特殊解决方案，如 CommonJS 和 AMD。ES6 模块可以使你自由、无缝地使用你最喜爱的 library 中那些最有用独立函数，而你的项目不必携带其他未使用的代码。ES6 模块最终还是要由浏览器原生实现，但当前 Rollup 可以使你提前体验。\n\n总而言之，rollup非常适合构建类库\n\n\u003e 本项目提供了多种较为完整使用案例, 体验方式\n\n\u003e npm install \u0026\u0026 npm run build \n\n\n## 安装方法\n\u003e 首先必须在node,npm环境下\n\n1. 全局安装： npm install rollup -g\n2. 项目安装： npm install rollup --save-dev 或者 yarn add rollup -D\n\n## 使用教程\n使用rollup构建js类库方法 有三种\n\n### 全局安装的可以直接使用rollup 命令行工具。\n\nrollup 常用命令 \n\u003e rollup 或者 rollup -h roll --help 相关api使用说明\n1. rollup -i, --input 必须传递的参数 ，打包的入口文件地址\n2. rollup -o 输出文件地址（不传递的话会显示在控制台）\n\n3. rollup -f 输出文件类型\n  + amd -- 异步模块定义，用于像RequestJS这样的模块加载器。\n  + cjs -- CommonJS, 适用于Node或Browserify/webpack\n  + es -- 将软件包保存为ES模块文件。\n  + iife -- 一个自动执行的功能，适合作为 script 标签这样的。只能在浏览器中运行\n  + umd -- 通用模块定义，以amd, cjs, 和 iife 为一体。\n\n4. rollup -n 生成umd模块名称，使用 umd 格式输出类型必须传递的参数\n5. rollup --watch 监听文件 是否改动 改动的话会重新构建打包\n\n6. rollup --silent 取消警告打印\n7. rollup --environment 设置构建时的环境变量\n   \u003e eg. rollup --enviroment INCLUDE_DEPS,BUILD:production\n   \u003e 相当于设置 Build = 'production' INCLUDE_DEPS = 'true'\n\n常用的命令行参数就这些, 比较完整的使用demo\n\n\u003e rollup -i ./src/index.js -o ./dist/index.js -f umd -n test --watch --silent\n\n### 局部安装的 通过使用配置文件 构建类库\n\n相比于命令后，配置文件构建的方式 可提供的配置选项更多，更常用.\n使用方法很简单在项目根目录创建 rollup.config.js, rollup 默认使用的是项目根目录的rollup.config.js文件的配置\nrollup.config.js的内容是一个es 模块.\n\n同样也可以使用命令行指定配置文件路径\nrollup -c,--config ./config/rollup.config.js\n\n配置文件选项具体如下：\n```js\n   // rollup.config.js\nexport default {\n  // 核心选项\n  input,     // 必须\n  external,\n  plugins,\n\n  // 额外选项\n  onwarn,\n\n  // danger zone\n  acorn,\n  context,\n  moduleContext,\n  legacy\n\n  output: {  // 必须 (如果要输出多个，可以是一个数组)\n    // 核心选项\n    file,    // 必须\n    format,  // 必须\n    name,\n    globals,\n\n    // 额外选项\n    paths,\n    banner,\n    footer,\n    intro,\n    outro,\n    sourcemap,\n    sourcemapFile,\n    interop,\n\n    // 高危选项\n    exports,\n    amd,\n    indent\n    strict\n  },\n};\n```\n#### 配置文件选项详解\n+ **input** (rollup -i,--input) 打包入口文件路径.\n  参数类型: String | String [] | { [entryName: string]: string }\n  *eg. input: ./src/index.js*\n  *eg. input: [./src/index.js, ./other/index.js]*\n  \u003e 注意 ：\n  \u003e 使用数组或者字符串作为选项值的时候的时候， 默认使用的是文件的原始名称， 作为文件的basename，可以在output:entryFileNames = 'entry-[name].js' 配置选项作为 '[name]' 动态参数传递进去\n  \n  *eg. input: { main: './src/index.js', vendor: './other/index.js' }*\n  \n  \u003e 注意：\n  \u003e 使用键值对{key: value}的选项值作为参数，使用的对象的键作为文件的basename， 用来在output:entryFileNames 配置选项作为 '[name]' 动态参数传递进去\n \n+ **plugins** 可以提供rollup 很多插件选项. 记住要调用导入的插件函数(即 commonjs(), 而不是 commonjs).\n  参数类型：Plugin | (Plugin | void)[]\n  ```js\n  {\n    ...,\n    plugins: [\n        resolve(), \n        commonjs()， \n        isProduction \u0026\u0026 (await import('rollup-plugin-terser')).terser()\n   ]\n  }\n  ```\n  \u003e 该用例 同时展示了如何动态控制在不同环境变量下构建使用不同的插件.\n+ **external** (rollup -e,--external) 维持包文件指定id文件维持外链，不参与打包构建\n    参数类型: String[] | (id: string, parentId: string, isResolved: boolean) =\u003e boolean.\n    ```js\n    {\n      ...,\n      external: [ \n          'some-externally-required-library',  \n          'another-externally-required-library'\n      ]\n    }\n    or \n    {\n      ...,\n      external: (id, parent, isResolved) =\u003e {\n        return true; \n      }\n    }\n    ```\n    \n    \u003e 1.当format类型为 iife 或者 umd 格式的时候 需要配置 output.globals 选项参数 以提供全局变量名来替换外部导入.\n    \u003e 2.当external是一个函数的时候。各个参数代表的含义分别是\n    \u003e id: 所有导入的文件id，（import访问的路径）\n    \u003e parent：import 所在的文件绝对路径\n    \u003e isResolved: 表示文件id是否已通过插件处理过\n    \n + **output** 是输出文件的统一配置入口, 包含很多可配置选项\n   参数类型：Object\n + **output.dir**(rollup -d,--dir) 配置文件打包后统一输出的基本目录，适用于多文件打包，单文件打包也可以用file选项代替\n   参数类型：String\n   *eg. ouput: { dir: './dist' }*\n \n + **output.file**(rollup -o,--file) 对于单个文件打包可以使用该选项指定打包内容写入带路径的文件。\n   参数类型：String\n   *eg. output: { file: './dist/index.js' }*\n + **output.format** (rollup -f,--format) 打包格式类型 ，配置可选项有（amd, cjs, es, iife, umd）选项说明同命令行配置选项.\n  参数类型: String\n  *eg. output: { format: iife }*\n+ **output.name** (rollup -n,--name) 代表你的 iife/umd 包，同一页上的其他脚本可以访问它.\n  参数类型: String\n  *eg. output: { name: MyLib }*\n+ **output.globals** (rollup -g,--globals) 配合配置external选项指定的外链 在**umd** 和 **iife** 文件类型下提供的全局访问变量名\n  参数类型: { [id: String]: String } | ((id: String) =\u003e String)  \n  ```js \n  {\n    ...,\n    external: ['./src/loadash.js']\n    output: { './src/loadash.js': '_' }\n  }\n  or\n  const externalId = path.resolve(__dirname, './src/jquery.js');\n  {\n    ...,\n    external: [externalId],\n    output: { \n        [externalId]: '$' \n    }\n  }\n  or\n  {\n    ...,\n    external: (id, parent, isResolved) =\u003e {\n        if(id === externalId \u0026\u0026 !isResolved) {\n            return true;\n        }\n        return false;\n    },\n    output: (id) =\u003e {\n        if(id === externalId) {\n            return '$'\n        }\n    }\n  }\n  ```\n  \u003e 注意：当使用函数作为globals指定项的时候 id 表示的是每一个导入文件的id（即访问路径的文件名）。\n\n* * *\n* * *\n#### 高级参数\n+ **manualChunks** 可以提取多个入口文件，共享的公共模块。\n  参数类型: { [chunkAlias: String]: String[] } | ((id: String) =\u003e String | void)\n  ```js\n  {\n    manualChunks: {\n      modal: ['./component/toast.js', './component/dialog.js'],\n      vendor: ['./redux.js', './react.js']\n    }\n  }\n  or \n  {\n    manualChunks: (id) =\u003e {\n      // 导入模块id 路径名\n      if(id.includes('node_modules')) {\n        return vendor;\n      }\n    } \n  }\n  ```\n  \u003e 注意：共享模块包包名是键值对模式 的 key + 文件hash 或者 函数返回值 + 文件hash, 在共享文件模块不发生改变的情况下 不会重新构建， 文件名也不会变。\n\n+ **output.banner/output.footer/output.intro / output.outro ** (rollup --banner/rollup --fotter) 额外添加捆绑包头信息和尾内容（可以添加一些版权注释等等）\n  参数类型：String | () =\u003e String | Promise\u003cString\u003e \n  ```js\n    {\n      ...,\n      output: {\n        ...,\n        banner: '/* my-library version ' + version + ' */',\n        footer: '/* follow me on Twitter! @rich_harris */',\n        intro: '/* this is a library */',\n        outro: '/* this is end */'\n      }\n    };\n  ```\n+ **output.assetFileNames** (rollup --assetFileNames) 资源文件打包变量名\n  默认值：\"assets/[name]-[hash][extname]\"\n  可以使用的动态变量。\n  \u003e 1. [extname] 文件扩展名 包括小数点 eg. .css/.img\n  \u003e 2. [ext] 文件扩展名 不包括小数点 eg css/img\n  \u003e 3. [hash] 文件名+内容的hash\n  \u003e 4. [name] 文件名\n  \n  默认配置，一般不建议修改 \n  \n+ **output.chunkFileNames** (rollup --chunkFileNames) 代码分割 共享chunk包的文件名\n  默认值：\"[name]-[hash].js\"\n  可以使用的动态变量。\n  \u003e 1. [format] 文件format 类型 e.g. esm/iife/umd/cjs\n  \u003e 3. [hash] 文件名+内容的hash\n  \u003e 4. [name] 文件名\n  \n  默认配置，一般不建议修改   \n  \n+ **output.entryFileNames** (rollup --entryFileNames) 入口文件input配置所指向的文件包名\n  默认值：\"[name].js\"\n  可以使用的动态变量。\n  \u003e 1. [format] 文件format 类型 e.g. esm/iife/umd/cjs\n  \u003e 3. [hash] 文件名+内容的hash\n  \u003e 4. [name] 文件名\n  \n  默认配置，一般不建议修改 \n  \n+ **output.compact** (rollup --compact/--no-compact) 打包文件是否压缩\n  参数类型：Boolean\n  默认值： false\n  *eg. { output: { compact: isProduction ? true : false }*\n  \u003e 该配置只会压缩打包后的有rollup生成的包装代码， 对于用户自己编写的代码不会改变 代码结构\n  \n\n+ **output.extend** (rollup --extend,--no-extend) 是否扩展 iife 或者umd格式定义的全局变量\n  参数类型：Boolean\n  默认值：false\n  *eg. { output: { extend: true } }*\n  \u003e 简单理解 这个参数的意思就是，当全局有定义 同样name 的全局变量的时候， 使用extend = true 打包的时候使用的是 global.name = global.name || {} 优先使用已经存在的变量， extend = false 的话就会直接覆盖该全局变量 gloabl.name = {};\n\n+ **output.sourcemap**(rollup -m,--sourcemap, --no-sourcemap) 创建源码的sourcemap\n  参数类型: Boolean | 'inline'\n  默认值: false\n  *eg. { output: { sourcemap: 'inline' } }*\n  \u003e 当sourcemap属性为true 的时候 ，会单独创建 sourcemap 源图文件， 当值为 inline 则会将源图数据uri 附加到源代码文件底部\n  \n+ **output.sourcemapPathTransform** 修改sourcemap指向的源文件路径\n  参数类型：(SourcePath: String) =\u003e String\n  ```js\n  {\n    output: {\n        sourcemap: true,\n        sourcemapPathTransform: (relativePath) =\u003e {\n            return relativePath.replace('src', 'anotherSrc');\n    }\n  }\n  ```\n  \u003e 应用场景很少， 在特殊场景 需要改变 sourcemap 的指向文件地址时才会用到\n  \n+ **strictDeprecations** (rollup --strictDeprecations,--no-strictDeprecations) 启用此标志后，当使用不推荐使用的功能时，Rollup将抛出错误而不是显示警告, 此外，标记为接收下一个主要版本的弃用警告的功能在使用时也会引发错误\n  参数类型: Boolean\n  *eg. { strictDeprecations: true }*\n* * *\n* * *\n#### 危险选项参数 \n\u003e 这里只介绍几个会用到的选项配置\n+ **acorn** 修改rollup解析js 配置\n  \u003e rollup 内部使用的[acorn](https://github.com/acornjs/acorn/tree/master/acorn#interface)库 解析js，[acorn](https://github.com/acornjs/acorn/tree/master/acorn#interface)库提供了解析js的相关 配置api，具体见[文档](https://github.com/acornjs/acorn/tree/master/acorn#interface)，一般很少需要修改，我也没怎么看。\n+ **acornInjectPlugins** 注入acornjs解析器插件\n  参数类型：AcornPluginFunction | AcornPluginFunction[]\n  ```js\n    import jsx from 'acorn-jsx';\n\n    export default {\n        // … other options …\n        acornInjectPlugins: [\n            jsx()\n        ]\n    };\n  ```\n  \u003e 注意：这个acorn-jsx 插件和 使用babel 并不是同一个意思，这个插件的左右是让 acorn js解析器能认识jsx语法，经过rollup打包后展示的还是jsx 语法，而babel 会直接修改jsx结构成为普通js 语法\n+ **treeshake** (rollup --treeshake,--no-treeshake)是否开启树摇 打包特性  \n  参数类型：Boolean | { annotations?: boolean, moduleSideEffects?: ModuleSideEffectsOption, propertyReadSideEffects?: boolean }\n  默认值： true\n  \u003e 不建议修改为false，除非树摇算法出现错误\n+ **treeshake.moduleSideEffects** 是否禁止空导入 \n  参数类型：Boolean | 'no-external'\n  默认值 true\n  \u003e 当moduleSideEffects为true 的时候 会删除 代码里面的空导入， eg. import './utils.js';\n  \u003e 当moduleSideEffects为'no-external'时，\n***\n***\n#### watch观察选项配置\n\u003e 这些选项仅在使用--watch标志运行Rollup 或使用rollup.watch\n\n+ **watch.chokidar** 代替node内置的文件监听 fs.watch 为 chokidar \n  参数类型：Boolean | ChokidarOptions\n  默认值：false\n  \u003e [chokidar](https://github.com/paulmillr/chokidar) 拥有比fs.watch 更好的展示体验，但是需要额外安装[chokidar](https://github.com/paulmillr/chokidar)\n+ **watch.clearScreen** 当rollup rebuild 的时候 是否需要清楚控制台内容\n  参数类型: Boolean\n  *eg. { watch: { clearScreen: true } }*\n+ **watch.exclude** 当rollup监视文件 需要排除的内容\n  参数类型: string\n  *eg. { watch: { exclude: 'node_modules/**' } }*  \n+ **watch.include** 指定rollup需要监听的具体文件\n  参数类型: string\n  *eg. { watch: { include: 'src/**' } }*  \n\n\u003e 常用的选项配置就是这些 下面提供一个较为完整的 配置文件demo \n\n```js\nimport path from 'path';\nexport default {\n    input: ['./src/index.js', './utils/index,js'],\n    external: [\n        path.resolve(__dirname, './src', 'dependA.js')\n    ],\n    output: {\n        dir: path.resolve(__dirname, '.', 'dist'),\n        format: 'cjs',\n        name: 'test',\n        entryFileNames: 'index-[name].js',\n        banner: '/* JohnApache JSLib */',\n        footer: '/* CopyRight */',\n        intro: 'const ENVIRONMENT = \"production\";',\n        outro: 'const ENVIRONMENT = \"development\";',\n        preserveModules: false,\n        sourcemap: true,\n        sourcemapPathTransform: (relativePath) =\u003e {\n             // will transform e.g. \"src/main.js\" -\u003e \"main.js\"\n             console.log(relativePath);\n             console.log(path.relative('src', relativePath));\n            return path.relative('src', relativePath)\n        }\n    },\n    preferConst: false,\n    manualChunks(id) {\n        if (id.includes('dependC')) {\n          return 'vendor';\n        }\n    }\n}\n\n```\n\n\n### 使用Javascript Api的方式构建打包程序\n\u003e rollup还提供了在nodejs中使用的api，相比于配置文件，直接使用rollup的nodeapi 可以提供更为复杂深奥的配置方式，以编程方式生成boundle\n+ rollup.js 详情  \n```js\nconst rollup = require('rollup');\n\n// see below for details on the options\nconst inputOptions = {...};\nconst outputOptions = {...};\n\nasync function build() {\n  // create a bundle\n  const bundle = await rollup.rollup(inputOptions);\n\n  console.log(bundle.watchFiles); // an array of file names this bundle depends on\n\n  // generate code\n  const { output } = await bundle.generate(outputOptions);\n\n  for (const chunkOrAsset of output) {\n    if (chunkOrAsset.isAsset) {\n      // For assets, this contains\n      // {\n      //   isAsset: true,                 // signifies that this is an asset\n      //   fileName: string,              // the asset file name\n      //   source: string | Buffer        // the asset source\n      // }\n      console.log('Asset', chunkOrAsset);\n    } else {\n      // For chunks, this contains\n      // {\n      //   code: string,                  // the generated JS code\n      //   dynamicImports: string[],      // external modules imported dynamically by the chunk\n      //   exports: string[],             // exported variable names\n      //   facadeModuleId: string | null, // the id of a module that this chunk corresponds to\n      //   fileName: string,              // the chunk file name\n      //   imports: string[],             // external modules imported statically by the chunk\n      //   isDynamicEntry: boolean,       // is this chunk a dynamic entry point\n      //   isEntry: boolean,              // is this chunk a static entry point\n      //   map: string | null,            // sourcemaps if present\n      //   modules: {                     // information about the modules in this chunk\n      //     [id: string]: {\n      //       renderedExports: string[]; // exported variable names that were included\n      //       removedExports: string[];  // exported variable names that were removed\n      //       renderedLength: number;    // the length of the remaining code in this module\n      //       originalLength: number;    // the original length of the code in this module\n      //     };\n      //   },\n      //   name: string                   // the name of this chunk as used in naming patterns\n      // }\n      console.log('Chunk', chunkOrAsset.modules);\n    }\n  }\n\n  // or write the bundle to disk\n  await bundle.write(outputOptions);\n}\n\nbuild();\n```\n+ inputOptions详情\n```js\n// inputOptions\nconst inputOptions = {\n  // core input options\n  external,\n  input, // required\n  plugins,\n\n  // advanced input options\n  cache,\n  inlineDynamicImports,\n  manualChunks,\n  onwarn,\n  preserveModules,\n  strictDeprecations,\n\n  // danger zone\n  acorn,\n  acornInjectPlugins,\n  context,\n  moduleContext,\n  preserveSymlinks,\n  shimMissingExports,\n  treeshake,\n\n  // experimental\n  chunkGroupingSize,\n  experimentalCacheExpiry,\n  experimentalOptimizeChunks,\n  experimentalTopLevelAwait,\n  perf\n};\n```\n+ outputOptions 详情\n```js\n//outputOptions\nconst outputOptions = {\n  // core output options\n  dir,\n  file,\n  format, // required\n  globals,\n  name,\n  \n  // advanced output options\n  assetFileNames,\n  banner,\n  chunkFileNames,\n  compact,\n  entryFileNames,\n  extend,\n  externalLiveBindings,\n  footer,\n  interop,\n  intro,\n  outro,\n  paths,\n  sourcemap,\n  sourcemapExcludeSources,\n  sourcemapFile,\n  sourcemapPathTransform,\n  \n  // danger zone\n  amd,\n  dynamicImportFunction,\n  esModule,\n  exports,\n  freeze,\n  indent,\n  namespaceToStringTag,\n  noConflict,\n  preferConst,\n  strict\n};\n```\n+ rollup 还提供了 监视api rollup.watch 可在检测到磁盘上的各个模块已更改时重建捆绑软件\n```js\nconst rollup = require('rollup');\n\nconst watchOptions = {...};\nconst watcher = rollup.watch(watchOptions);\n\nwatcher.on('event', event =\u003e {\n  // event.code can be one of:\n  //   START        — the watcher is (re)starting\n  //   BUNDLE_START — building an individual bundle\n  //   BUNDLE_END   — finished building a bundle\n  //   END          — finished building all bundles\n  //   ERROR        — encountered an error while bundling\n  //   FATAL        — encountered an unrecoverable error\n});\n\n// stop watching\nwatcher.close();\n```\n+ watchOptions详情\n```js\nconst watchOptions = {\n  ...inputOptions,\n  output: [outputOptions],\n  watch: {\n    chokidar,\n    clearScreen,\n    exclude,\n    include\n  }\n};\n```\n\n### rollup 常用插件介绍\n+ **rollup-plugin-node-resolve** 帮助rollup 查找node_modules里的三方模块\n  \u003e 使用方法：\n  ```js\n    import resolve from 'rollup-plugin-node-resolve';\n    {\n        ...\n        plugins: [\n           resolve() \n        ]\n    }\n  ```\n+ **rollup-plugin-commonjs** 帮助rollup查找commonjs 规范的模块, 常配合rollup-plugin-node-resolve一起使用\n   \u003e 使用方法\n   ```js\n    import common from 'rollup-plugin-commonjs';\n    {\n        ...\n        plugins: [\n           resolve() \n           common({\n               include: 'node_modules/**', // 包括\n              exclude: [],  // 排除\n           })\n        ]\n    }\n  ```\n+ **rollup-plugin-terser** 可以打包压缩es6的js代码\n  \u003e 使用方法\n  ```js\n    import {terser} from 'rollup-plugin-terser';\n    import os from 'os';\n    const cpuNums = os.cpus().length;\n    {\n        ...\n        plugins: [\n           terser({\n             output: {\n                comments: false,\n             },\n             numWorkers: cpuNums, //多线程压缩\n             sourcemap: false,\n             include: [/^.+\\.js$/],\n             exclude: [ 'node_modules/**' ]\n           })\n        ]\n    }\n  ```\n+ **rollup-plugin-uglify** 可以打包压缩es6的js代码\n  \u003e 使用方法 \n  ```js\n    import {uglify} from 'rollup-plugin-terser';\n    import os from 'os';\n    const cpuNums = os.cpus().length;\n    {\n        ...\n        plugins: [\n           uglify({\n             output: {\n                comments: false,\n             },\n             numWorkers: cpuNums, //多线程压缩\n             sourcemap: false,\n           })\n        ]\n    }\n  ```  \n  \u003e 注意 :\n  \u003e 1. uglify插件 会运行在每一个chunk包里面\n  \u003e 2. uglify 和 babel code frame一起使用会报错\n  \u003e 3. uglify 不支持es6语法，\n  \u003e 综上建议直接使用rollup-plugin-terser， 完美解决上述所有问题\n  \n+ **rollup-plugin-babel** 打包的时候使用babel编译js代码 \n  \u003e 使用说明 使用前需要安装babel环境, 这里使用的babel 7.x\n  \u003e npm install @babel/cli @babel/core @babel/polyfill @babel/preset-env @babel/plugin-transform-runtime --save-dev \n  \u003e npm install @babel/runtime-corejs3\n  ```js\n    // rollup.config.js\n    import babel from 'rollup-plugin-babel';\n    export default {\n        ...,\n        plugins: [\n            babel({\n               runtimeHelpers: true,\n            }),\n        ]\n    }\n  ```\n  ```js\n  // babel.config.js\n  const presets = [\n    '@babel/env'\n  ]\n\n  const plugins = [\n      [\n          '@babel/plugin-transform-runtime',\n          {\n              corejs: 3\n          }\n      ]\n  ]\n  module.exports = {\n      presets,\n      plugins,\n  }\n  ```\n\n+ **rollup-plugin-typescript2**\n    \u003e 这是对原始rollup-plugin-typescript的重写，这个版本比原始版本慢一些，但是它将打印出打字稿的句法和语义诊断消息（毕竟使用打字稿的主要原因）。使用该插件还有一个重要的原因，该插件能生成 声明文件\n    \n    \u003e 首先需要提供基础安装环境, 除了typescript基础环境 该插件需要依赖tslib去编译ts 代码\n    ```shell\n    yarn add rollup-plugin-typescript2 typescript tslib -D\n    ```\n    \n    使用方法很简单\n    ```js\n    // rollup.config.js\n    import typescript from 'rollup-plugin-typescript2';\n    import commonjs from 'rollup-plugin-commonjs';\n    export default {\n        ...,\n         plugins: [\n            typescript({\n                tsconfigOverride: {\n                    compilerOptions: {\n                        module: \"ES2015\",\n                        target: \"ES2015\"\n                    }\n                }\n            }),\n            commonjs({\n                extensions: ['.js', '.ts']\n            })\n        ],\n    }\n    ```\n\n\u003e TIP: 官方维护的新版插件集合[https://github.com/rollup/plugins](https://github.com/rollup/plugins);\n\n## TODO\n### rollup 插件的开发\n。。。\n### rollup 配合gulp 工作流\n。。。\n\n\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjohnapache%2Frollup-usage-doc","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fjohnapache%2Frollup-usage-doc","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fjohnapache%2Frollup-usage-doc/lists"}