关于rollup:入门rollup

5次阅读

共计 1365 个字符,预计需要花费 4 分钟才能阅读完成。

overview

以一个最根本的 demo 展现 rollup 的性能 / 用法。

init project

mkdir exRollup
cd exRollup
npm init
npm i -d rollup
npm i -d rollup-plugin-json

编辑 package.json

{
  ...
  "scripts": {
      ...
    "build:cjs": "rollup -c ./config/rollup.config.cjs.js",
    "build:esm": "rollup -c ./config/rollup.config.esm.js",
    "build:iife": "rollup -c ./config/rollup.config.iife.js",
    "build:umd": "rollup -c ./config/rollup.config.umd.js",
    "build": "npm run build.cjs & npm run build:esm & npm run build:iife & npm run build:cmd"
  }
}

编辑配置文件

本示例中有 4 个配置文件。别离用于生成 commonjs 标准代码 /esm标准代码 / 立刻执行代码 /umd标准代码。

// rollup.config.cjs.js
import json from 'rollup-plugin-json';

export default {
  input: 'src/index.js',
  output: {
    file: 'dist/bundle.cjs.js',
    format: 'cjs'
  },
  plugins: [json() ]
};
// rollup.config.esm.js
import json from 'rollup-plugin-json';

export default {
  input: 'src/index.js',
  output: {
    file: 'dist/bundle.esm.js',
    format: 'esm'
  },
  plugins: [json() ]
};
// rollup.config.iife.js
import json from 'rollup-plugin-json';

export default {
  input: 'src/index.js',
  output: {
    file: 'dist/bundle.iife.js',
    format: 'iife'
  },
  plugins: [json() ]
};
// rollup.config.umd.js
import json from 'rollup-plugin-json';

export default {
  input: 'src/index.js',
  output: {
    file: 'dist/bundle.umd.js',
    format: 'umd'
  },
  plugins: [json() ]
};

编辑代码

// src/foo.js
export default function (a, b) {return a + b}
// src/index.js
import {version} from '../package.json'
import add from './foo.js'
export default function () {console.log(`version: ${version}`)
}
export let sum = function (a, b) {return add(a, b)
}

执行打包

npm run build
正文完
 0