Rollup


rollup的基本使用

Rollup是一个 JavaScript 模块打包器,可以将小块代码编译成大块复杂的代码,Rollup 对代码模块使用新的标准化格式,这些标准都包含在 JavaScript 的 ES6 版本中

npm i rollup -D

使用rollup编译文件

浏览器环境

rollup main.js --file bundle.js --format iife

编译node

rollup main.js --file bundle.js --format cjs

使用rollup配置文件

export default {
    // 入口文件
    input: 'src/main.js',
    output: {
        // 输出文件
        file: 'dist/bundle.js',
        // 输出文件的格式
        format: 'iife'
    }
}

Rollup插件

插件是Rollup唯一的拓展途径

下面以rollup-plugin-json为例

+ import json from 'rollup-plugin-json'

export default {
    input: 'src/main.js',
    output: {
        file: 'dist/bundle.js',
        format: 'iife'
    },
+    plugins:[
+        json()
+    ]
}

使用rollup加载npm模块

rollup默认只支持路径加载,可以通过使用@rollup/plugin-node-resolve像webpack一样通过模块名称倒入模块

+ import resolve from '@rollup/plugin-node-resolve'

export default {
    input: 'src/main.js',
    output: {
        file: 'dist/bundle.js',
        format: 'iife'
    },
    plugins:[
+        resolve()
    ]
}

使rollup支导入commonjs模块

+ import commonjs from '@rollup/plugin-commonjs'

export default {
    input: 'src/main.js',
    output: {
        file: 'dist/bundle.js',
        format: 'iife'
    },
    plugins:[
+        commonjs()
    ]
}

代码拆分

Rollup已经支持动态导入

import('./a').then({sum} => {
    console.log(sum)
})

注意,这里umdiife不支持代码拆分

export default {
    input: 'src/main.js',
    output: {
        format: 'amd',
        dir: 'dist'
    }
}

多入口打包

Rollup多入口打包的写法与Webpack类似

export default {
    input: ['src/a.js', 'src/b.js'],
    output: {
        format: 'amd',
        dir: 'dist'
    }
}
export default {
    input: {
        main: './a.js',
        b: './b.js'
    },
    output: {
        format: 'amd',
        dir: 'dist'
    }
}

Rollup选用原则

  • 加载非ESM的第三方模块比较复杂
  • 浏览器环境中,代码拆分功能依赖AMD库(代码拆分不支持UMD和IIFE)

文章作者: Shibin
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 Shibin !
  目录