-
Notifications
You must be signed in to change notification settings - Fork 508
/
createRollupConfig.ts
216 lines (204 loc) · 6.2 KB
/
createRollupConfig.ts
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
import { DEFAULT_EXTENSIONS } from '@babel/core';
import { safeVariableName, safePackageName, external } from './utils';
import { paths } from './constants';
import { terser } from 'rollup-plugin-terser';
import babel from 'rollup-plugin-babel';
import commonjs from 'rollup-plugin-commonjs';
import json from 'rollup-plugin-json';
import replace from 'rollup-plugin-replace';
import resolve from 'rollup-plugin-node-resolve';
import sourceMaps from 'rollup-plugin-sourcemaps';
import typescript from 'rollup-plugin-typescript2';
import { extractErrors } from './errors/extractErrors';
const replacements = [{ original: 'lodash', replacement: 'lodash-es' }];
const errorCodeOpts = {
errorMapFilePath: paths.appRoot + '/errors/codes.json',
};
interface TsdxOptions {
input: string;
name: string;
target: 'node' | 'browser';
env: 'development' | 'production';
tsconfig?: string;
extractErrors?: string;
minify?: boolean;
}
const babelOptions = (format: 'cjs' | 'esm' | 'umd', opts: TsdxOptions) => ({
exclude: 'node_modules/**',
extensions: [...DEFAULT_EXTENSIONS, 'ts', 'tsx'],
passPerPreset: true, // @see https://babeljs.io/docs/en/options#passperpreset
presets: [
[
require.resolve('@babel/preset-env'),
{
loose: true,
modules: false,
targets: opts.target === 'node' ? { node: '8' } : undefined,
exclude: ['transform-async-to-generator'],
},
],
],
plugins: [
require.resolve('babel-plugin-annotate-pure-calls'),
require.resolve('babel-plugin-dev-expression'),
format !== 'cjs' && [
require.resolve('babel-plugin-transform-rename-import'),
{ replacements },
],
[
require.resolve('babel-plugin-transform-async-to-promises'),
{ inlineHelpers: true, externalHelpers: true },
],
[
require.resolve('@babel/plugin-proposal-class-properties'),
{ loose: true },
],
opts.extractErrors && require('./errors/transformErrorMessages'),
].filter(Boolean),
});
// shebang cache map thing because the transform only gets run once
let shebang: any = {};
export function createRollupConfig(
format: 'cjs' | 'umd' | 'esm',
opts: TsdxOptions
) {
const findAndRecordErrorCodes = extractErrors({
...errorCodeOpts,
...opts,
});
const shouldMinify =
opts.minify !== undefined ? opts.minify : opts.env === 'production';
const outputName = [
`${paths.appDist}/${safePackageName(opts.name)}`,
format,
opts.env,
shouldMinify ? 'min' : '',
'js',
]
.filter(Boolean)
.join('.');
return {
// Tell Rollup the entry point to the package
input: opts.input,
// Tell Rollup which packages to ignore
external: (id: string) => {
if (id === 'babel-plugin-transform-async-to-promises/helpers') {
return false;
}
return external(id);
},
// Establish Rollup output
output: {
// Set filenames of the consumer's package
file: outputName,
// Pass through the file format
format,
// Do not let Rollup call Object.freeze() on namespace import objects
// (i.e. import * as namespaceImportObject from...) that are accessed dynamically.
freeze: false,
// Do not let Rollup add a `__esModule: true` property when generating exports for non-ESM formats.
esModule: false,
// Rollup has treeshaking by default, but we can optimize it further...
treeshake: {
// We assume reading a property of an object never has side-effects.
// This means tsdx WILL remove getters and setters on objects.
//
// @example
//
// const foo = {
// get bar() {
// console.log('effect');
// return 'bar';
// }
// }
//
// const result = foo.bar;
// const illegalAccess = foo.quux.tooDeep;
//
// Punchline....Don't use getters and setters
propertyReadSideEffects: false,
},
name: opts.name || safeVariableName(opts.name),
sourcemap: true,
globals: { react: 'React', 'react-native': 'ReactNative' },
exports: 'named',
},
plugins: [
!!opts.extractErrors && {
transform(source: any) {
findAndRecordErrorCodes(source);
return source;
},
},
resolve({
mainFields: [
'module',
'main',
opts.target !== 'node' ? 'browser' : undefined,
].filter(Boolean) as string[],
}),
format === 'umd' &&
commonjs({
// use a regex to make sure to include eventual hoisted packages
include: /\/node_modules\//,
}),
json(),
{
// Custom plugin that removes shebang from code because newer
// versions of bublé bundle their own private version of `acorn`
// and I don't know a way to patch in the option `allowHashBang`
// to acorn. Taken from microbundle.
// See: https://github.com/Rich-Harris/buble/pull/165
transform(code: string) {
let reg = /^#!(.*)/;
let match = code.match(reg);
shebang[opts.name] = match ? '#!' + match[1] : '';
code = code.replace(reg, '');
return {
code,
map: null,
};
},
},
typescript({
typescript: require('typescript'),
cacheRoot: `./.rts2_cache_${format}`,
tsconfig: opts.tsconfig,
tsconfigDefaults: {
compilerOptions: {
sourceMap: true,
declaration: true,
jsx: 'react',
},
},
tsconfigOverride: {
compilerOptions: {
target: 'esnext',
},
},
}),
babel(babelOptions(format, opts)),
opts.env !== undefined &&
replace({
'process.env.NODE_ENV': JSON.stringify(opts.env),
}),
sourceMaps(),
// sizeSnapshot({
// printInfo: false,
// }),
shouldMinify &&
terser({
sourcemap: true,
output: { comments: false },
compress: {
keep_infinity: true,
pure_getters: true,
passes: 10,
},
ecma: 5,
toplevel: format === 'cjs',
warnings: true,
}),
],
};
}