-
Notifications
You must be signed in to change notification settings - Fork 0
/
rollup.config.js
238 lines (220 loc) · 6.09 KB
/
rollup.config.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
// more see http://rollupjs.org/guide/en/#configuration-files
import virtual from '@rollup/plugin-virtual';
import { nodeResolve } from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
import json from '@rollup/plugin-json';
import url from '@rollup/plugin-url';
import styles from 'rollup-plugin-styles';
import { babel } from '@rollup/plugin-babel';
import esbuild from 'rollup-plugin-esbuild';
import { terser } from 'rollup-plugin-terser';
import replace from '@rollup/plugin-replace';
import strip from '@rollup/plugin-strip';
import progress from 'rollup-plugin-progress';
import filesize from 'rollup-plugin-filesize';
import visualizer from 'rollup-plugin-visualizer';
// node
import process from 'process';
import path from 'path';
import { URL, fileURLToPath } from 'url';
import fse from 'fs-extra';
// ! 项目目录
const WORKING_DIRECTORY = fileURLToPath(new URL('.', import.meta.url));
console.log('current working directory: ' + WORKING_DIRECTORY);
// ! 脚本必须在项目根目录执行,防止脚本执行错误
if (!fse.pathExistsSync(path.join(WORKING_DIRECTORY, 'package.json'))) {
throw new Error(
'The package.json file does not exist in the current working directory.\n'
);
}
// ! 清空构建目录
fse.emptyDirSync(path.join(WORKING_DIRECTORY, 'build/'));
const args = process.argv.slice(2);
let serve = args.findIndex((item) => item.trim() === '--serve');
if (serve > -1) {
args.splice(serve, 1);
serve = true;
} else {
serve = false;
}
// * 开启服务
let browserSync;
if (serve) {
browserSync = require('./scripts/serve.cjs').browserSync;
}
function reloadServerPlugin() {
return {
name: 'reload-server',
writeBundle() {
if (browserSync) {
browserSync.reload();
}
},
};
}
const NUMBER_KB = 1024;
const NUMBER_1000 = 1000;
const babelConfig = require('./.babelrc.cjs');
const isEnvDevelopment = String(process.env.NODE_ENV).trim() === 'development';
const isEnvProduction =
String(process.env.NODE_ENV).trim() === 'production' || !isEnvDevelopment;
const pkg = fse.readJSONSync('./package.json', { encoding: 'utf8' });
// 暴露的全局变量名称
const name = 'myLib';
const banner = () => {
// see docs: https://github.com/terser/terser#keeping-copyright-notices-or-other-comments
return `/*!
* ${pkg.name}
* @description ${pkg.description}
* @version ${pkg.version}
* @date ${new Date().toLocaleString()}
* @author ${pkg.author}
*/`;
};
/**
* @param {'esm' | 'umd'} format
* @param {'' | 'min'} minimize
* @returns
*/
function getBundleFile(format, minimize = '') {
return `build/bundle.${format}${minimize ? `.${minimize}` : ''}.js`;
}
/**
* @type {import('rollup').RollupOptions}
*/
const configBuilder = ({ keepDebug = false, env = 'development' } = {}) => ({
cache: isEnvDevelopment,
watch: {
include: 'src/**',
},
onwarn: (warning, warn) => {
if (warning.code === 'CIRCULAR_DEPENDENCY') {
return;
}
warn(warning);
},
treeshake: isEnvProduction,
input: 'src/index.ts',
output: [
// * UMD
isEnvProduction && {
file: getBundleFile('umd'),
format: 'umd',
name,
banner,
sourcemap: true,
},
// * ES module
{
file: getBundleFile('esm'),
format: 'es',
banner,
sourcemap: true,
plugins: [isEnvDevelopment && reloadServerPlugin()].filter(Boolean),
},
].filter(Boolean),
plugins: [
// ! 将调试包的代码剥离
!keepDebug &&
virtual({
ajv: 'export default {}',
'src/helper/validate': 'export default {}',
}),
commonjs({ sourceMap: isEnvDevelopment }),
nodeResolve({ browser: true, extensions: ['.ts', '.js'] }),
replace({
preventAssignment: true,
values: {
'process.env.NODE_ENV': JSON.stringify(
keepDebug ? env : process.env.NODE_ENV
),
},
}),
json(),
url({
// limit: NUMBER_KB * NUMBER_1000,
limit: Infinity,
fileName: '[name]-[hash][extname]',
}),
styles({
autoModules: (id) => id.includes('.module.'),
minimize: isEnvProduction,
sourceMap: isEnvDevelopment,
// sourceMap: [true, { content: false }]
}),
isEnvDevelopment &&
esbuild({
target: 'esnext',
}),
// 编译,兼容性处理,注入 polyfills
isEnvProduction &&
babel({
...babelConfig,
babelrc: false,
exclude: [/* /\/node_modules\//, */ /\/core-js\//],
extensions: ['.ts', '.js'],
babelHelpers: 'runtime',
}),
!keepDebug &&
isEnvProduction &&
strip({ include: ['src/**/*.js', 'src/**/*.ts'] }),
isEnvProduction &&
progress({
clearLine: false, // default: true
}),
isEnvProduction && filesize(),
].filter(Boolean),
external: [],
});
/**
* 生产包
* @type {import('rollup').RollupOptions}
*/
const productionConfig = {
...configBuilder(),
output: [
// * UMD
isEnvProduction && {
file: getBundleFile('umd', 'min'),
format: 'umd',
name,
banner,
sourcemap: true,
plugins: [terser({ mangle: { safari10: true, reserved: [] } })],
},
// * ES module
isEnvProduction && {
file: getBundleFile('esm', 'min'),
format: 'es',
banner,
sourcemap: true,
plugins: [
terser({ mangle: { safari10: true, reserved: [] } }),
isEnvProduction &&
visualizer({
sourcemap: true,
open: true,
gzipSize: true,
brotliSize: false,
}),
].filter(Boolean),
},
].filter(Boolean),
};
const exportConfig = [configBuilder({ keepDebug: true })];
if (isEnvProduction) {
exportConfig.push(productionConfig);
}
// 生成类型定义入口文件
function generateTypesEntryFile(config) {
config.output.forEach((item) => {
const bundleFile = path.join(WORKING_DIRECTORY, item.file);
fse.outputFileSync(
bundleFile.replace(path.extname(bundleFile), '.d.ts'),
'export * from "../types"',
{ encoding: 'utf-8' }
);
});
}
exportConfig.forEach((config) => generateTypesEntryFile(config));
export default exportConfig;