-
-
Notifications
You must be signed in to change notification settings - Fork 531
/
swc.ts
270 lines (251 loc) · 8.97 KB
/
swc.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
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
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
import type * as ts from 'typescript';
import type * as swcWasm from '@swc/wasm';
import type * as swcTypes from '@swc/core';
import type { CreateTranspilerOptions, Transpiler } from './types';
import type { NodeModuleEmitKind } from '..';
import { getUseDefineForClassFields } from '../ts-internals';
type SwcInstance = typeof swcTypes;
export interface SwcTranspilerOptions extends CreateTranspilerOptions {
/**
* swc compiler to use for compilation
* Set to '@swc/wasm' to use swc's WASM compiler
* Default: '@swc/core', falling back to '@swc/wasm'
*/
swc?: string | typeof swcWasm;
}
export function create(createOptions: SwcTranspilerOptions): Transpiler {
const {
swc,
service: { config, projectLocalResolveHelper },
transpilerConfigLocalResolveHelper,
nodeModuleEmitKind,
} = createOptions;
// Load swc compiler
let swcInstance: SwcInstance;
// Used later in diagnostics; merely needs to be human-readable.
let swcDepName: string = 'swc';
if (typeof swc === 'string') {
swcDepName = swc;
swcInstance = require(transpilerConfigLocalResolveHelper(swc, true)) as SwcInstance;
} else if (swc == null) {
let swcResolved;
try {
swcDepName = '@swc/core';
swcResolved = transpilerConfigLocalResolveHelper(swcDepName, true);
} catch (e) {
try {
swcDepName = '@swc/wasm';
swcResolved = transpilerConfigLocalResolveHelper(swcDepName, true);
} catch (e) {
throw new Error(
'swc compiler requires either @swc/core or @swc/wasm to be installed as a dependency. See https://typestrong.org/ts-node/docs/transpilers'
);
}
}
swcInstance = require(swcResolved) as SwcInstance;
} else {
swcInstance = swc as any as SwcInstance;
}
// Prepare SWC options derived from typescript compiler options
const { nonTsxOptions, tsxOptions } = createSwcOptions(config.options, nodeModuleEmitKind, swcInstance, swcDepName);
const transpile: Transpiler['transpile'] = (input, transpileOptions) => {
const { fileName } = transpileOptions;
const swcOptions = fileName.endsWith('.tsx') || fileName.endsWith('.jsx') ? tsxOptions : nonTsxOptions;
const { code, map } = swcInstance.transformSync(input, {
...swcOptions,
filename: fileName,
});
return { outputText: code, sourceMapText: map };
};
return {
transpile,
};
}
/** @internal */
export const targetMapping = new Map<ts.ScriptTarget, SwcTarget>();
targetMapping.set(/* ts.ScriptTarget.ES3 */ 0, 'es3');
targetMapping.set(/* ts.ScriptTarget.ES5 */ 1, 'es5');
targetMapping.set(/* ts.ScriptTarget.ES2015 */ 2, 'es2015');
targetMapping.set(/* ts.ScriptTarget.ES2016 */ 3, 'es2016');
targetMapping.set(/* ts.ScriptTarget.ES2017 */ 4, 'es2017');
targetMapping.set(/* ts.ScriptTarget.ES2018 */ 5, 'es2018');
targetMapping.set(/* ts.ScriptTarget.ES2019 */ 6, 'es2019');
targetMapping.set(/* ts.ScriptTarget.ES2020 */ 7, 'es2020');
targetMapping.set(/* ts.ScriptTarget.ES2021 */ 8, 'es2021');
targetMapping.set(/* ts.ScriptTarget.ES2022 */ 9, 'es2022');
targetMapping.set(/* ts.ScriptTarget.ESNext */ 99, 'esnext');
type SwcTarget = typeof swcTargets[number];
/**
* @internal
* We use this list to downgrade to a prior target when we probe swc to detect if it supports a particular target
*/
const swcTargets = [
'es3',
'es5',
'es2015',
'es2016',
'es2017',
'es2018',
'es2019',
'es2020',
'es2021',
'es2022',
'esnext',
] as const;
const ModuleKind = {
None: 0,
CommonJS: 1,
AMD: 2,
UMD: 3,
System: 4,
ES2015: 5,
ES2020: 6,
ESNext: 99,
Node16: 100,
NodeNext: 199,
} as const;
const JsxEmit = {
ReactJSX: /* ts.JsxEmit.ReactJSX */ 4,
ReactJSXDev: /* ts.JsxEmit.ReactJSXDev */ 5,
} as const;
/**
* Prepare SWC options derived from typescript compiler options.
* @internal exported for testing
*/
export function createSwcOptions(
compilerOptions: ts.CompilerOptions,
nodeModuleEmitKind: NodeModuleEmitKind | undefined,
swcInstance: SwcInstance,
swcDepName: string
) {
const {
esModuleInterop,
sourceMap,
importHelpers,
experimentalDecorators,
emitDecoratorMetadata,
target,
module,
jsx,
jsxFactory,
jsxFragmentFactory,
strict,
alwaysStrict,
noImplicitUseStrict,
jsxImportSource,
} = compilerOptions;
let swcTarget = targetMapping.get(target!) ?? 'es3';
// Downgrade to lower target if swc does not support the selected target.
// Perhaps project has an older version of swc.
// TODO cache the results of this; slightly faster
let swcTargetIndex = swcTargets.indexOf(swcTarget);
for (; swcTargetIndex >= 0; swcTargetIndex--) {
try {
swcInstance.transformSync('', {
jsc: { target: swcTargets[swcTargetIndex] as swcWasm.JscTarget },
});
break;
} catch (e) {}
}
swcTarget = swcTargets[swcTargetIndex];
const keepClassNames = target! >= /* ts.ScriptTarget.ES2016 */ 3;
const isNodeModuleKind = module === ModuleKind.Node16 || module === ModuleKind.NodeNext;
// swc only supports these 4x module options [MUST_UPDATE_FOR_NEW_MODULEKIND]
const moduleType =
module === ModuleKind.CommonJS
? 'commonjs'
: module === ModuleKind.AMD
? 'amd'
: module === ModuleKind.UMD
? 'umd'
: isNodeModuleKind && nodeModuleEmitKind === 'nodecjs'
? 'commonjs'
: isNodeModuleKind && nodeModuleEmitKind === 'nodeesm'
? 'es6'
: 'es6';
// In swc:
// strictMode means `"use strict"` is *always* emitted for non-ES module, *never* for ES module where it is assumed it can be omitted.
// (this assumption is invalid, but that's the way swc behaves)
// tsc is a bit more complex:
// alwaysStrict will force emitting it always unless `import`/`export` syntax is emitted which implies it per the JS spec.
// if not alwaysStrict, will emit implicitly whenever module target is non-ES *and* transformed module syntax is emitted.
// For node, best option is to assume that all scripts are modules (commonjs or esm) and thus should get tsc's implicit strict behavior.
// Always set strictMode, *unless* alwaysStrict is disabled and noImplicitUseStrict is enabled
const strictMode =
// if `alwaysStrict` is disabled, remembering that `strict` defaults `alwaysStrict` to true
(alwaysStrict === false || (alwaysStrict !== true && strict !== true)) &&
// if noImplicitUseStrict is enabled
noImplicitUseStrict === true
? false
: true;
const jsxRuntime: swcTypes.ReactConfig['runtime'] =
jsx === JsxEmit.ReactJSX || jsx === JsxEmit.ReactJSXDev ? 'automatic' : undefined;
const jsxDevelopment: swcTypes.ReactConfig['development'] = jsx === JsxEmit.ReactJSXDev ? true : undefined;
const useDefineForClassFields = getUseDefineForClassFields(compilerOptions);
const nonTsxOptions = createVariant(false);
const tsxOptions = createVariant(true);
return { nonTsxOptions, tsxOptions };
function createVariant(isTsx: boolean): swcTypes.Options {
const swcOptions: swcTypes.Options = {
sourceMaps: sourceMap,
// isModule: true,
module: moduleType
? {
type: moduleType,
...(moduleType === 'amd' || moduleType === 'commonjs' || moduleType === 'umd'
? {
noInterop: !esModuleInterop,
strictMode,
// For NodeNext and Node12, emit as CJS but do not transform dynamic imports
ignoreDynamic: nodeModuleEmitKind === 'nodecjs',
}
: {}),
}
: undefined,
swcrc: false,
jsc: {
externalHelpers: importHelpers,
parser: {
syntax: 'typescript',
tsx: isTsx,
decorators: experimentalDecorators,
dynamicImport: true,
importAssertions: true,
} as swcWasm.TsParserConfig,
target: swcTarget as swcWasm.JscTarget,
transform: {
decoratorMetadata: emitDecoratorMetadata,
legacyDecorator: true,
react: {
throwIfNamespace: false,
development: jsxDevelopment,
useBuiltins: false,
pragma: jsxFactory!,
pragmaFrag: jsxFragmentFactory!,
runtime: jsxRuntime,
importSource: jsxImportSource,
},
useDefineForClassFields,
},
keepClassNames,
experimental: {
keepImportAttributes: true,
emitAssertForImportAttributes: true,
} as swcTypes.JscConfig['experimental'],
},
};
// Throw a helpful error if swc version is old, for example, if it rejects `ignoreDynamic`
try {
swcInstance.transformSync('', swcOptions);
} catch (e) {
throw new Error(
`${swcDepName} threw an error when attempting to validate swc compiler options.\n` +
'You may be using an old version of swc which does not support the options used by ts-node.\n' +
'Try upgrading to the latest version of swc.\n' +
'Error message from swc:\n' +
(e as Error)?.message
);
}
return swcOptions;
}
}