Rollup从0到1上手前端组件库开发 | CJS插件

774 阅读2分钟

小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。

Rollup从0到1上手前端组件库开发 | CJS插件

上文回顾

CommonJS插件

commonJS 是 通过 require 引入模块 module.export 输出模块

为什么使用 commonjs 插件?

rollup.js 默认是不支持 CommonJS模块的

举个例子

  • 在 src 目录下 创建 cjs.js
const a = 1
module.exports = a
  • 在 index.js 文件中使用
import data from './cjs.js'

console.log(data);

export default data
  • babel-node 执行 /src/index.js
npx babel-node ./src/index.js
1
# 执行是可以成功的
  • rollup 打包编译 yarn dev
Error: 'default' is not exported by src/cjs.js, imported by src/index.js
# 编译失败

那么如何才能打包成功呢? 来试试 commonjs插件吧

commonjs插件的使用方法

  • 安装commonjs插件 yarn add rollup-plugin-commonjs -D

  • 修改 rollup.config.dev.js 配置文件

vim rollup.config.dev.js

const path = require('path')
const resolve = require("rollup-plugin-node-resolve")\
// 导入 commonjs 插件
const commonjs = require('rollup-plugin-commonjs')
const inputPath = path.resolve(__dirname, "./src/index.js")
const outputUmdPath = path.resolve(__dirname, "./dist/payfun.rollbear.dev.js")
const outputEsPath = path.resolve(__dirname, "./dist/payfun.rollbear.dev.es.js") 
console.log(inputPath)
module.exports = {
    input: inputPath,
    output: [
        {
            file: outputUmdPath, // 输出路径
            format: 'umd', // 输出的模块协议 umd
            name: "payfunRollbear" // 模块名称
        },
        {
            file: outputEsPath, // 输出路径
            format: 'es', // 输出的模块协议 es
            name: "payfunRollbear" // 模块名称
        }
    ],
    plugins: [
        resolve(),
        commonjs(), // 使用commonjs 插件
    ],
    external: ['decimal.js', 'vue'], 
}

  • 再看一下rollup 编译结果

vim dist/payfun.rollbear.dev.es.js

const a = 1;

var cjs = a;

// import {Decimal} from 'decimal.js';

console.log(cjs);

export { cjs as default }

编译成功~!

通过 commonjs 插件 可以有效解决 在rollup开发中 commonjs模块无法被识别的问题

Commonjs 中如何 tree shaking

// cjs.js
// 此时使用commonjs默认方式进行输出 , 不会被 tree shaking
const a = 1
const b = 2
module.exports = {
	a,b
}
// 可以被tree shaking的方式
exports.a = 1
exports.b = 2