Rollup

Tips#

npm install --global rollup
# 常用插件
yarn add -D rollup @babel/core @rollup/plugin-babel rollup-plugin-terser @rollup/plugin-node-resolve
# Babel + Typescript
yarn add -D @babel/preset-env @babel/preset-typescript
# + React
yarn add -D @babel/preset-react
# yarn add -D rollup @rollup/plugin-commonjs @rollup/plugin-node-resolve @rollup/plugin-babel
# yarn add -D @babel/core @babel/preset-typescript @babel/preset-react @babel/plugin-proposal-decorators @babel/plugin-proposal-class-properties
# TS - 但目前不好用
yarn add -D typescript tslib @rollup/plugin-typescript
FormatFullnameWhenpackage.json
amdAsynchronous Module DefinitionRequireJS
cjs,commonjsCommonJSNodemain
es,esm,module<script type=module>module
iifeself-executing function<script>
Application
umdUniversal Module Definitionamd, cjs, iifebrowser
system,systemjsSystemJSSystemJS

配置#

yarn add -D @babel/core @rollup/plugin-babel rollup-plugin-terser @rollup/plugin-node-resolve

rollup commonjs#

import commonjs from '@rollup/plugin-commonjs';
import { nodeResolve } from '@rollup/plugin-node-resolve';
import babel from '@rollup/plugin-babel';
function createConfig(format) {
return {
input: 'src/index.ts',
output: {
file: `dist/console-feed.${format}.js`,
sourcemap: true,
format,
},
external: [
'react',
],
plugins: [
nodeResolve({ browser: true, extensions: ['.js', '.jsx', '.ts', '.tsx'] }),
babel({
babelHelpers: 'bundled',
babelrc: false,
presets: [['@babel/preset-typescript',{allowNamespaces:true}], '@babel/preset-react'],
plugins: [
['@babel/plugin-proposal-decorators', { legacy: true }],
['@babel/plugin-proposal-class-properties', { loose: true }],
],
extensions: ['.js', '.jsx', '.ts', '.tsx'],
}),
commonjs({ extensions: ['.js', '.jsx', '.ts', '.tsx'] }),
],
};
}
export default [createConfig('system'),createConfig('umd')];

插件#

rollup-plugin-replace#

  • 替代进行优化
require('rollup-plugin-replace')({
'process.env.NODE_ENV': JSON.stringify('production')
})

babel#

FAQ#

this has been rewritten to undefined#

  • 配合 typescript 会出现,不影响使用,但很烦

忽略该错误

{
onwarn(warning) {
if (warning.code === 'THIS_IS_UNDEFINED') {
return;
}
console.warn('THIS_IS_UNDEFINED', warning.message);
},
}

Rollup requires that your Babel configuration keeps ES6 module syntax intact.#

{
plugins: [
babel({
babelHelpers: 'bundled',
babelrc: false,
}),
terser({ ecma: 6, module: true }),
],
}

SyntaxError: Unexpected token: punc (.)#

Missing class properties transform.#

  • @babel/plugin-proposal-class-properties

'default' is not exported by#

  • 导入方式的问题
// 这样不会使用 default
// TS 中的 allowSyntheticDefaultImports 参数
import * as Abc from './abc'

xxx.default is not a function#

  • 一般是 commonjs 的问题

可以手动添加命名导出

commonjs({
include: 'node_modules/**',
// 新版本插件会自带处理,没有了该参数
namedExports: {
'node_modules/@emotion/memoize/dist/memoize.cjs.js':['memoize']
},
}),

'default' is not exported by#

  • commonjs 问题