Vite 中文文档 Vite 中文文档
指南
GitHub (opens new window)
指南
GitHub (opens new window)
  • vite

    • 指引
    • 为什么选 Vite
    • 开始
    • 功能
    • 命令行界面
    • 使用插件
    • 依赖预构建
    • 静态资源处理
    • 构建生产版本
    • 部署静态站点
    • 环境变量和模式
    • 服务端渲染
    • 后端集成
    • 与其他工具比较
    • 故障排除
    • 从 v3 迁移
  • API

  • 配置参考

  • vite

  • API

  • 配置参考

Rollup 使用教程


概述


引用官方的一句话

Rollup 是一个 JavaScript 模块打包器,可以将小块代码编译成大块复杂的代码,例如 library 或应用程序。Rollup 对代码模块使用新的标准化格式,这些标准都包含在 JavaScript 的 ES6 版本中,而不是以前的特殊解决方案,如 CommonJS 和 AMD。ES6 模块可以使你自由、无缝地使用你最喜爱的 library 中那些最有用独立函数,而你的项目不必携带其他未使用的代码。ES6 模块最终还是要由浏览器原生实现,但当前 Rollup 可以使你提前体验。


总而言之,rollup非常适合构建类库

本项目提供了多种较为完整使用案例, 体验方式


npm install && npm run build


安装方法


首先必须在node,npm环境下


全局安装: npm install rollup -g
项目安装: npm install rollup --save-dev 或者 yarn add rollup -D

使用教程


使用rollup构建js类库方法 有三种

全局安装的可以直接使用rollup 命令行工具。


rollup 常用命令

rollup 或者 rollup -h roll --help 相关api使用说明


rollup -i, --input 必须传递的参数 ,打包的入口文件地址

rollup -o 输出文件地址(不传递的话会显示在控制台)

rollup -f 输出文件类型

amd -- 异步模块定义,用于像RequestJS这样的模块加载器。
cjs -- CommonJS, 适用于Node或Browserify/webpack
es -- 将软件包保存为ES模块文件。
iife -- 一个自动执行的功能,适合作为 script 标签这样的。只能在浏览器中运行
umd -- 通用模块定义,以amd, cjs, 和 iife 为一体。

rollup -n 生成umd模块名称,使用 umd 格式输出类型必须传递的参数

rollup --watch 监听文件 是否改动 改动的话会重新构建打包

rollup --silent 取消警告打印

rollup --environment 设置构建时的环境变量

eg. rollup --enviroment INCLUDE_DEPS,BUILD:production 相当于设置 Build = 'production' INCLUDE_DEPS = 'true'


常用的命令行参数就这些, 比较完整的使用demo

rollup -i ./src/index.js -o ./dist/index.js -f umd -n test --watch --silent


局部安装的 通过使用配置文件 构建类库


相比于命令后,配置文件构建的方式 可提供的配置选项更多,更常用. 使用方法很简单在项目根目录创建 rollup.config.js, rollup 默认使用的是项目根目录的rollup.config.js文件的配置 rollup.config.js的内容是一个es 模块.

同样也可以使用命令行指定配置文件路径 rollup -c,--config ./config/rollup.config.js

配置文件选项具体如下:

  1. ``` js
  2.    // rollup.config.js
  3. export default {
  4.   // 核心选项
  5.   input,     // 必须
  6.   external,
  7.   plugins,

  8.   // 额外选项
  9.   onwarn,

  10.   // danger zone
  11.   acorn,
  12.   context,
  13.   moduleContext,
  14.   legacy

  15.   output: {  // 必须 (如果要输出多个,可以是一个数组)
  16.     // 核心选项
  17.     file,    // 必须
  18.     format,  // 必须
  19.     name,
  20.     globals,

  21.     // 额外选项
  22.     paths,
  23.     banner,
  24.     footer,
  25.     intro,
  26.     outro,
  27.     sourcemap,
  28.     sourcemapFile,
  29.     interop,

  30.     // 高危选项
  31.     exports,
  32.     amd,
  33.     indent
  34.     strict
  35.   },
  36. };
  37. ```

配置文件选项详解


input(rollup -i,--input) 打包入口文件路径. 参数类型: String | String [] | { [entryName: string]: string } eg. input: ./src/index.jseg. input: [./src/index.js, ./other/index.js]

注意 : 使用数组或者字符串作为选项值的时候的时候, 默认使用的是文件的原始名称, 作为文件的basename,可以在output:entryFileNames = 'entry-[name].js' 配置选项作为 '[name]' 动态参数传递进去


eg. input: { main: './src/index.js', vendor: './other/index.js' }

注意: 使用键值对{key: value}的选项值作为参数,使用的对象的键作为文件的basename, 用来在output:entryFileNames 配置选项作为 '[name]' 动态参数传递进去


plugins可以提供rollup 很多插件选项. 记住要调用导入的插件函数(即 commonjs(), 而不是 commonjs). 参数类型:Plugin | (Plugin | void)[]

  1. ``` js
  2. {
  3.   ...,
  4.   plugins: [
  5.       resolve(),
  6.       commonjs(),
  7.       isProduction && (await import('rollup-plugin-terser')).terser()
  8. ]
  9. }
  10. ```

该用例 同时展示了如何动态控制在不同环境变量下构建使用不同的插件.


external(rollup -e,--external) 维持包文件指定id文件维持外链,不参与打包构建 参数类型: String[] | (id: string, parentId: string, isResolved: boolean) => boolean.

  1. ``` js
  2. {
  3.   ...,
  4.   external: [
  5.       'some-externally-required-library',  
  6.       'another-externally-required-library'
  7.   ]
  8. }
  9. or
  10. {
  11.   ...,
  12.   external: (id, parent, isResolved) => {
  13.     return true;
  14.   }
  15. }
  16. ```

1.当format类型为 iife 或者 umd 格式的时候 需要配置 output.globals 选项参数 以提供全局变量名来替换外部导入. 2.当external是一个函数的时候。各个参数代表的含义分别是 id: 所有导入的文件id,(import访问的路径) parent:import 所在的文件绝对路径 isResolved: 表示文件id是否已通过插件处理过


output是输出文件的统一配置入口, 包含很多可配置选项 参数类型:Object

output.dir(rollup -d,--dir) 配置文件打包后统一输出的基本目录,适用于多文件打包,单文件打包也可以用file选项代替 参数类型:String eg. ouput: { dir: './dist' }

output.file(rollup -o,--file) 对于单个文件打包可以使用该选项指定打包内容写入带路径的文件。 参数类型:String eg. output: { file: './dist/index.js' }

output.format(rollup -f,--format) 打包格式类型 ,配置可选项有(amd, cjs, es, iife, umd)选项说明同命令行配置选项. 参数类型: String eg. output: { format: iife }

output.name(rollup -n,--name) 代表你的 iife/umd 包,同一页上的其他脚本可以访问它. 参数类型: String eg. output: { name: MyLib }

output.globals(rollup -g,--globals) 配合配置external选项指定的外链 在umd和 iife文件类型下提供的全局访问变量名 参数类型: { [id: String]: String } | ((id: String) => String)

  1. ``` js
  2. {
  3.   ...,
  4.   external: ['./src/loadash.js']
  5.   output: { './src/loadash.js': '_' }
  6. }
  7. or
  8. const externalId = path.resolve(__dirname, './src/jquery.js');
  9. {
  10.   ...,
  11.   external: [externalId],
  12.   output: {
  13.       [externalId]: '<%= main %>#39;
  14.   }
  15. }
  16. or
  17. {
  18.   ...,
  19.   external: (id, parent, isResolved) => {
  20.       if(id === externalId && !isResolved) {
  21.           return true;
  22.       }
  23.       return false;
  24.   },
  25.   output: (id) => {
  26.       if(id === externalId) {
  27.           return '<%= main %>#39;
  28.       }
  29.   }
  30. }
  31. ```

注意:当使用函数作为globals指定项的时候 id 表示的是每一个导入文件的id(即访问路径的文件名)。


高级参数


manualChunks可以提取多个入口文件,共享的公共模块。 参数类型: { [chunkAlias: String]: String[] } | ((id: String) => String | void)

  1. ``` js
  2. {
  3.   manualChunks: {
  4.     modal: ['./component/toast.js', './component/dialog.js'],
  5.     vendor: ['./redux.js', './react.js']
  6.   }
  7. }
  8. or
  9. {
  10.   manualChunks: (id) => {
  11.     // 导入模块id 路径名
  12.     if(id.includes('node_modules')) {
  13.       return vendor;
  14.     }
  15.   }
  16. }
  17. ```

注意:共享模块包包名是键值对模式 的 key + 文件hash 或者 函数返回值 + 文件hash, 在共享文件模块不发生改变的情况下 不会重新构建, 文件名也不会变。


output.banner/output.footer/output.intro / output.outro (rollup --banner/rollup --fotter) 额外添加捆绑包头信息和尾内容(可以添加一些版权注释等等) 参数类型:String | () => String | Promise

  1. ``` js
  2.   {
  3.     ...,
  4.     output: {
  5.       ...,
  6.       banner: '/* my-library version ' + version + ' */',
  7.       footer: '/* follow me on Twitter! @rich_harris */',
  8.       intro: '/* this is a library */',
  9.       outro: '/* this is end */'
  10.     }
  11.   };
  12. ```

output.assetFileNames(rollup --assetFileNames) 资源文件打包变量名 默认值:"assets/[name]-[hash][extname]" 可以使用的动态变量。

[extname] 文件扩展名 包括小数点 eg. .css/.img
[ext] 文件扩展名 不包括小数点 eg css/img
[hash] 文件名+内容的hash
[name] 文件名

默认配置,一般不建议修改

output.chunkFileNames(rollup --chunkFileNames) 代码分割 共享chunk包的文件名 默认值:"[name]-[hash].js" 可以使用的动态变量。

[format] 文件format 类型 e.g. esm/iife/umd/cjs
[hash] 文件名+内容的hash
[name] 文件名

默认配置,一般不建议修改

output.entryFileNames(rollup --entryFileNames) 入口文件input配置所指向的文件包名 默认值:"[name].js" 可以使用的动态变量。

[format] 文件format 类型 e.g. esm/iife/umd/cjs
[hash] 文件名+内容的hash
[name] 文件名

默认配置,一般不建议修改

output.compact(rollup --compact/--no-compact) 打包文件是否压缩 参数类型:Boolean 默认值: false eg. { output: { compact: isProduction ? true : false }

该配置只会压缩打包后的有rollup生成的包装代码, 对于用户自己编写的代码不会改变 代码结构


output.extend(rollup --extend,--no-extend) 是否扩展 iife 或者umd格式定义的全局变量 参数类型:Boolean 默认值:false eg. { output: { extend: true } }

简单理解 这个参数的意思就是,当全局有定义 同样name 的全局变量的时候, 使用extend = true 打包的时候使用的是 global.name = global.name || {} 优先使用已经存在的变量, extend = false 的话就会直接覆盖该全局变量 gloabl.name = {};


output.sourcemap(rollup -m,--sourcemap, --no-sourcemap) 创建源码的sourcemap 参数类型: Boolean | 'inline' 默认值: false eg. { output: { sourcemap: 'inline' } }

当sourcemap属性为true 的时候 ,会单独创建 sourcemap 源图文件, 当值为 inline 则会将源图数据uri 附加到源代码文件底部


output.sourcemapPathTransform修改sourcemap指向的源文件路径 参数类型:(SourcePath: String) => String

  1. ``` js
  2. {
  3.   output: {
  4.       sourcemap: true,
  5.       sourcemapPathTransform: (relativePath) => {
  6.           return relativePath.replace('src', 'anotherSrc');
  7.   }
  8. }
  9. ```

应用场景很少, 在特殊场景 需要改变 sourcemap 的指向文件地址时才会用到


strictDeprecations(rollup --strictDeprecations,--no-strictDeprecations) 启用此标志后,当使用不推荐使用的功能时,Rollup将抛出错误而不是显示警告, 此外,标记为接收下一个主要版本的弃用警告的功能在使用时也会引发错误 参数类型: Boolean eg. { strictDeprecations: true }

危险选项参数


这里只介绍几个会用到的选项配置


acorn修改rollup解析js 配置 > rollup 内部使用的acorn 库 解析js,acorn 库提供了解析js的相关 配置api,具体见文档 ,一般很少需要修改,我也没怎么看。

acornInjectPlugins注入acornjs解析器插件 参数类型:AcornPluginFunction | AcornPluginFunction[]
  1. ``` js
  2.   import jsx from 'acorn-jsx';

  3.   export default {
  4.       // … other options …
  5.       acornInjectPlugins: [
  6.           jsx()
  7.       ]
  8.   };
  9. ```

注意:这个acorn-jsx 插件和 使用babel 并不是同一个意思,这个插件的左右是让 acorn js解析器能认识jsx语法,经过rollup打包后展示的还是jsx 语法,而babel 会直接修改jsx结构成为普通js 语法


treeshake(rollup --treeshake,--no-treeshake)是否开启树摇 打包特性参数类型:Boolean | { annotations?: boolean, moduleSideEffects?: ModuleSideEffectsOption, propertyReadSideEffects?: boolean } 默认值: true > 不建议修改为false,除非树摇算法出现错误

treeshake.moduleSideEffects是否禁止空导入 参数类型:Boolean | 'no-external' 默认值 true > 当moduleSideEffects为true 的时候 会删除 代码里面的空导入, eg. import './utils.js'; 当moduleSideEffects为'no-external'时,

watch观察选项配置


这些选项仅在使用--watch标志运行Rollup 或使用rollup.watch


watch.chokidar代替node内置的文件监听 fs.watch 为 chokidar 参数类型:Boolean | ChokidarOptions 默认值:false > chokidar 拥有比fs.watch 更好的展示体验,但是需要额外安装chokidar

watch.clearScreen当rollup rebuild 的时候 是否需要清楚控制台内容 参数类型: Boolean eg. { watch: { clearScreen: true } }
watch.exclude当rollup监视文件 需要排除的内容 参数类型: string eg. { watch: { exclude: 'node_modules/' } }
watch.include指定rollup需要监听的具体文件 参数类型: string eg. { watch: { include: 'src/' } }

常用的选项配置就是这些 下面提供一个较为完整的 配置文件demo


  1. ``` js
  2. import path from 'path';
  3. export default {
  4.     input: ['./src/index.js', './utils/index,js'],
  5.     external: [
  6.         path.resolve(__dirname, './src', 'dependA.js')
  7.     ],
  8.     output: {
  9.         dir: path.resolve(__dirname, '.', 'dist'),
  10.         format: 'cjs',
  11.         name: 'test',
  12.         entryFileNames: 'index-[name].js',
  13.         banner: '/* JohnApache JSLib */',
  14.         footer: '/* CopyRight */',
  15.         intro: 'const ENVIRONMENT = "production";',
  16.         outro: 'const ENVIRONMENT = "development";',
  17.         preserveModules: false,
  18.         sourcemap: true,
  19.         sourcemapPathTransform: (relativePath) => {
  20.              // will transform e.g. "src/main.js" -> "main.js"
  21.              console.log(relativePath);
  22.              console.log(path.relative('src', relativePath));
  23.             return path.relative('src', relativePath)
  24.         }
  25.     },
  26.     preferConst: false,
  27.     manualChunks(id) {
  28.         if (id.includes('dependC')) {
  29.           return 'vendor';
  30.         }
  31.     }
  32. }
  33. ```

使用Javascript Api的方式构建打包程序


rollup还提供了在nodejs中使用的api,相比于配置文件,直接使用rollup的nodeapi 可以提供更为复杂深奥的配置方式,以编程方式生成boundle


rollup.js 详情

  1. ``` js
  2. const rollup = require('rollup');

  3. // see below for details on the options
  4. const inputOptions = {...};
  5. const outputOptions = {...};

  6. async function build() {
  7.   // create a bundle
  8.   const bundle = await rollup.rollup(inputOptions);

  9.   console.log(bundle.watchFiles); // an array of file names this bundle depends on

  10.   // generate code
  11.   const { output } = await bundle.generate(outputOptions);

  12.   for (const chunkOrAsset of output) {
  13.     if (chunkOrAsset.isAsset) {
  14.       // For assets, this contains
  15.       // {
  16.       //   isAsset: true,                 // signifies that this is an asset
  17.       //   fileName: string,              // the asset file name
  18.       //   source: string | Buffer        // the asset source
  19.       // }
  20.       console.log('Asset', chunkOrAsset);
  21.     } else {
  22.       // For chunks, this contains
  23.       // {
  24.       //   code: string,                  // the generated JS code
  25.       //   dynamicImports: string[],      // external modules imported dynamically by the chunk
  26.       //   exports: string[],             // exported variable names
  27.       //   facadeModuleId: string | null, // the id of a module that this chunk corresponds to
  28.       //   fileName: string,              // the chunk file name
  29.       //   imports: string[],             // external modules imported statically by the chunk
  30.       //   isDynamicEntry: boolean,       // is this chunk a dynamic entry point
  31.       //   isEntry: boolean,              // is this chunk a static entry point
  32.       //   map: string | null,            // sourcemaps if present
  33.       //   modules: {                     // information about the modules in this chunk
  34.       //     [id: string]: {
  35.       //       renderedExports: string[]; // exported variable names that were included
  36.       //       removedExports: string[];  // exported variable names that were removed
  37.       //       renderedLength: number;    // the length of the remaining code in this module
  38.       //       originalLength: number;    // the original length of the code in this module
  39.       //     };
  40.       //   },
  41.       //   name: string                   // the name of this chunk as used in naming patterns
  42.       // }
  43.       console.log('Chunk', chunkOrAsset.modules);
  44.     }
  45.   }

  46.   // or write the bundle to disk
  47.   await bundle.write(outputOptions);
  48. }

  49. build();
  50. ```

inputOptions详情

  1. ``` js
  2. // inputOptions
  3. const inputOptions = {
  4.   // core input options
  5.   external,
  6.   input, // required
  7.   plugins,

  8.   // advanced input options
  9.   cache,
  10.   inlineDynamicImports,
  11.   manualChunks,
  12.   onwarn,
  13.   preserveModules,
  14.   strictDeprecations,

  15.   // danger zone
  16.   acorn,
  17.   acornInjectPlugins,
  18.   context,
  19.   moduleContext,
  20.   preserveSymlinks,
  21.   shimMissingExports,
  22.   treeshake,

  23.   // experimental
  24.   chunkGroupingSize,
  25.   experimentalCacheExpiry,
  26.   experimentalOptimizeChunks,
  27.   experimentalTopLevelAwait,
  28.   perf
  29. };
  30. ```

outputOptions 详情

  1. ``` js
  2. //outputOptions
  3. const outputOptions = {
  4.   // core output options
  5.   dir,
  6.   file,
  7.   format, // required
  8.   globals,
  9.   name,

  10.   // advanced output options
  11.   assetFileNames,
  12.   banner,
  13.   chunkFileNames,
  14.   compact,
  15.   entryFileNames,
  16.   extend,
  17.   externalLiveBindings,
  18.   footer,
  19.   interop,
  20.   intro,
  21.   outro,
  22.   paths,
  23.   sourcemap,
  24.   sourcemapExcludeSources,
  25.   sourcemapFile,
  26.   sourcemapPathTransform,

  27.   // danger zone
  28.   amd,
  29.   dynamicImportFunction,
  30.   esModule,
  31.   exports,
  32.   freeze,
  33.   indent,
  34.   namespaceToStringTag,
  35.   noConflict,
  36.   preferConst,
  37.   strict
  38. };
  39. ```

rollup 还提供了 监视api rollup.watch 可在检测到磁盘上的各个模块已更改时重建捆绑软件

  1. ``` js
  2. const rollup = require('rollup');

  3. const watchOptions = {...};
  4. const watcher = rollup.watch(watchOptions);

  5. watcher.on('event', event => {
  6.   // event.code can be one of:
  7.   //   START        — the watcher is (re)starting
  8.   //   BUNDLE_START — building an individual bundle
  9.   //   BUNDLE_END   — finished building a bundle
  10.   //   END          — finished building all bundles
  11.   //   ERROR        — encountered an error while bundling
  12.   //   FATAL        — encountered an unrecoverable error
  13. });

  14. // stop watching
  15. watcher.close();
  16. ```

watchOptions详情

  1. ``` js
  2. const watchOptions = {
  3.   ...inputOptions,
  4.   output: [outputOptions],
  5.   watch: {
  6.     chokidar,
  7.     clearScreen,
  8.     exclude,
  9.     include
  10.   }
  11. };
  12. ```

rollup 常用插件介绍


rollup-plugin-node-resolve帮助rollup 查找node_modules里的三方模块

使用方法:


  1. ``` js
  2.   import resolve from 'rollup-plugin-node-resolve';
  3.   {
  4.       ...
  5.       plugins: [
  6.          resolve()
  7.       ]
  8.   }
  9. ```

rollup-plugin-commonjs帮助rollup查找commonjs 规范的模块, 常配合rollup-plugin-node-resolve一起使用

使用方法


  1. ``` js
  2. import common from 'rollup-plugin-commonjs';
  3. {
  4.      ...
  5.      plugins: [
  6.         resolve()
  7.         common({
  8.             include: 'node_modules/**', // 包括
  9.            exclude: [],  // 排除
  10.         })
  11.      ]
  12. }
  13. ```

rollup-plugin-terser可以打包压缩es6的js代码

使用方法


  1. ``` js
  2.   import {terser} from 'rollup-plugin-terser';
  3.   import os from 'os';
  4.   const cpuNums = os.cpus().length;
  5.   {
  6.       ...
  7.       plugins: [
  8.          terser({
  9.            output: {
  10.               comments: false,
  11.            },
  12.            numWorkers: cpuNums, //多线程压缩
  13.            sourcemap: false,
  14.            include: [/^.+\.js$/],
  15.            exclude: [ 'node_modules/**' ]
Last Updated: 2023-08-06 19:18:07