File size: 7,855 Bytes
1e92f2d |
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 239 240 241 242 243 244 245 246 |
import { safeVariableName, safePackageName, external } from './utils';
import { paths } from './constants';
import { RollupOptions } from 'rollup';
import { terser } from 'rollup-plugin-terser';
import { DEFAULT_EXTENSIONS as DEFAULT_BABEL_EXTENSIONS } from '@babel/core';
import commonjs from '@rollup/plugin-commonjs';
import json from '@rollup/plugin-json';
import replace from '@rollup/plugin-replace';
import resolve, {
DEFAULTS as RESOLVE_DEFAULTS,
} from '@rollup/plugin-node-resolve';
import sourceMaps from 'rollup-plugin-sourcemaps';
import typescript from 'rollup-plugin-typescript2';
import ts from 'typescript';
import { extractErrors } from './errors/extractErrors';
import { babelPluginTsdx } from './babelPluginTsdx';
import { TsdxOptions } from './types';
const errorCodeOpts = {
errorMapFilePath: paths.appErrorsJson,
};
// shebang cache map thing because the transform only gets run once
let shebang: any = {};
export async function createRollupConfig(
opts: TsdxOptions,
outputNum: number
): Promise<RollupOptions> {
const findAndRecordErrorCodes = await extractErrors({
...errorCodeOpts,
...opts,
});
const isEsm = opts.format.includes('es') || opts.format.includes('esm');
const shouldMinify =
opts.minify !== undefined ? opts.minify : opts.env === 'production' || isEsm;
let formatString = ['esm', 'cjs'].includes(opts.format) ? '' : opts.format;
let fileExtension = opts.format === 'esm' ? 'mjs' : 'cjs';
const outputName = [
`${paths.appDist}/${safePackageName(opts.name)}`,
formatString,
opts.env,
shouldMinify ? 'min' : '',
fileExtension,
]
.filter(Boolean)
.join('.');
const tsconfigPath = opts.tsconfig || paths.tsconfigJson;
// borrowed from https://github.com/facebook/create-react-app/pull/7248
const tsconfigJSON = ts.readConfigFile(tsconfigPath, ts.sys.readFile).config;
// borrowed from https://github.com/ezolenko/rollup-plugin-typescript2/blob/42173460541b0c444326bf14f2c8c27269c4cb11/src/parse-tsconfig.ts#L48
const tsCompilerOptions = ts.parseJsonConfigFileContent(
tsconfigJSON,
ts.sys,
'./'
).options;
return {
// Tell Rollup the entry point to the package
input: opts.input,
// Tell Rollup which packages to ignore
external: (id: string) => {
// bundle in polyfills as TSDX can't (yet) ensure they're installed as deps
if (id.startsWith('regenerator-runtime')) {
return false;
}
return external(id);
},
// 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 defined directly on objects.
// Any getters or setters defined on classes will not be effected.
//
// @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,
},
// Establish Rollup output
output: {
// Set filenames of the consumer's package
file: outputName,
// Pass through the file format
format: opts.format,
// Do not let Rollup call Object.freeze() on namespace import objects
// (i.e. import * as namespaceImportObject from...) that are accessed dynamically.
freeze: false,
// Respect tsconfig esModuleInterop when setting __esModule.
esModule: Boolean(tsCompilerOptions?.esModuleInterop),
name: opts.name || safeVariableName(opts.name),
sourcemap: true,
globals: { react: 'React', 'react-native': 'ReactNative', 'lodash-es': 'lodashEs', 'lodash/fp': 'lodashFp' },
exports: 'named',
},
plugins: [
!!opts.extractErrors && {
async transform(code: string) {
try {
await findAndRecordErrorCodes(code);
} catch (e) {
return null;
}
return { code, map: null };
},
},
resolve({
mainFields: [
'module',
'main',
opts.target !== 'node' ? 'browser' : undefined,
].filter(Boolean) as string[],
extensions: [...RESOLVE_DEFAULTS.extensions, '.cjs', '.mjs', '.jsx'],
}),
// all bundled external modules need to be converted from CJS to ESM
commonjs({
// use a regex to make sure to include eventual hoisted packages
include:
opts.format === 'umd'
? /\/node_modules\//
: /\/regenerator-runtime\//,
}),
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: ts,
tsconfig: opts.tsconfig,
tsconfigDefaults: {
exclude: [
// all TS test files, regardless whether co-located or in test/ etc
'**/*.spec.ts',
'**/*.test.ts',
'**/*.spec.tsx',
'**/*.test.tsx',
// TS defaults below
'node_modules',
'bower_components',
'jspm_packages',
paths.appDist,
],
compilerOptions: {
sourceMap: true,
declaration: true,
jsx: 'react',
},
},
tsconfigOverride: {
compilerOptions: {
// TS -> esnext, then leave the rest to babel-preset-env
target: 'esnext',
// don't output declarations more than once
...(outputNum > 0
? { declaration: false, declarationMap: false }
: {}),
},
},
check: !opts.transpileOnly && outputNum === 0,
useTsconfigDeclarationDir: Boolean(tsCompilerOptions?.declarationDir),
}),
babelPluginTsdx({
exclude: 'node_modules/**',
extensions: [...DEFAULT_BABEL_EXTENSIONS, 'ts', 'tsx'],
passPerPreset: true,
custom: {
targets: opts.target === 'node' ? { node: '14' } : undefined,
extractErrors: opts.extractErrors,
format: opts.format,
},
babelHelpers: 'bundled',
}),
opts.env !== undefined &&
replace({
preventAssignment: true,
'process.env.NODE_ENV': JSON.stringify(opts.env),
}),
sourceMaps(),
shouldMinify &&
terser({
output: { comments: false },
compress: {
keep_infinity: true,
pure_getters: true,
passes: 10,
},
ecma: opts.legacy ? 5 : 2020,
module: isEsm,
toplevel: opts.format === 'cjs' || isEsm,
warnings: true,
}),
/**
* Ensure there's an empty default export to prevent runtime errors.
*
* @see https://www.npmjs.com/package/rollup-plugin-export-default
*/
{
renderChunk: async (code: string, chunk: any) => {
if (chunk.exports.includes('default') || !isEsm) {
return null;
}
return {
code: `${code}\nexport default {};`,
map: null,
};
},
},
],
};
}
|