-
Notifications
You must be signed in to change notification settings - Fork 3.2k
/
index.js
249 lines (219 loc) · 8.56 KB
/
index.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
239
240
241
242
243
244
245
246
247
248
249
const path = require('path')
const fs = require('fs-extra')
const JSON5 = require('json5')
const webpack = require('webpack')
const Debug = require('debug')
const webpackPreprocessor = require('@cypress/webpack-preprocessor')
const debug = Debug('cypress:webpack-batteries-included-preprocessor')
const hasTsLoader = (rules) => {
return rules.some((rule) => {
if (!rule.use || !Array.isArray(rule.use)) return false
return rule.use.some((use) => {
return use.loader && use.loader.includes('ts-loader')
})
})
}
const getTSCompilerOptionsForUser = (configFilePath) => {
const compilerOptions = {
sourceMap: false,
inlineSourceMap: true,
inlineSources: true,
downlevelIteration: true,
}
if (!configFilePath) {
return compilerOptions
}
try {
// If possible, try to read the user's tsconfig.json and see if sourceMap is configured
// eslint-disable-next-line no-restricted-syntax
const tsconfigJSON = fs.readFileSync(configFilePath, 'utf8')
// file might have trailing commas, new lines, etc. JSON5 can parse those correctly
const parsedJSON = JSON5.parse(tsconfigJSON)
// if the user has sourceMap's configured, set the option to true and turn off inlineSourceMaps
if (parsedJSON?.compilerOptions?.sourceMap) {
compilerOptions.sourceMap = true
compilerOptions.inlineSourceMap = false
compilerOptions.inlineSources = false
}
} catch (e) {
debug(`error in getTSCompilerOptionsForUser. Returning default...`, e)
} finally {
return compilerOptions
}
}
const addTypeScriptConfig = (file, options) => {
// shortcut if we know we've already added typescript support
if (options.__typescriptSupportAdded) return options
const webpackOptions = options.webpackOptions
const rules = webpackOptions.module && webpackOptions.module.rules
// if there are no rules defined or it's not an array, we can't add to them
if (!rules || !Array.isArray(rules)) return options
// if we find ts-loader configured, don't add it again
if (hasTsLoader(rules)) return options
const TsconfigPathsPlugin = require('tsconfig-paths-webpack-plugin')
// node will try to load a projects tsconfig.json instead of the node
// package using require('tsconfig'), so we alias it as 'tsconfig-aliased-for-wbip'
const configFile = require('tsconfig-aliased-for-wbip').findSync(path.dirname(file.filePath))
const compilerOptions = getTSCompilerOptionsForUser(configFile)
webpackOptions.module.rules.push({
test: /\.tsx?$/,
exclude: [/node_modules/],
use: [
{
loader: require.resolve('ts-loader'),
options: {
compiler: options.typescript,
compilerOptions,
logLevel: 'error',
silent: true,
transpileOnly: true,
},
},
],
})
webpackOptions.resolve.extensions = webpackOptions.resolve.extensions.concat(['.ts', '.tsx'])
webpackOptions.resolve.plugins = [new TsconfigPathsPlugin({
configFile,
silent: true,
})]
options.__typescriptSupportAdded = true
return options
}
const getDefaultWebpackOptions = () => {
return {
mode: 'development',
node: {
global: true,
__filename: true,
__dirname: true,
},
module: {
rules: [{
test: /\.mjs$/,
include: /node_modules/,
exclude: [/browserslist/],
type: 'javascript/auto',
}, {
test: /(\.jsx?|\.mjs)$/,
exclude: [/node_modules/, /browserslist/],
type: 'javascript/auto',
use: [{
loader: require.resolve('babel-loader'),
options: {
plugins: [
...[
'babel-plugin-add-module-exports',
'@babel/plugin-transform-class-properties',
'@babel/plugin-transform-object-rest-spread',
].map(require.resolve),
[require.resolve('@babel/plugin-transform-runtime'), {
absoluteRuntime: path.dirname(require.resolve('@babel/runtime/package')),
}],
],
presets: [
// the chrome version should be synced with
// packages/web-config/webpack.config.base.ts and
// packages/server/lib/browsers/chrome.ts
[require.resolve('@babel/preset-env'), { modules: 'commonjs', targets: { 'chrome': '64' } }],
require.resolve('@babel/preset-react'),
],
configFile: false,
babelrc: false,
},
}],
}, {
test: /\.coffee$/,
exclude: [/node_modules/, /browserslist/],
loader: require.resolve('coffee-loader'),
}],
},
plugins: [
new webpack.ProvidePlugin({
Buffer: ['buffer', 'Buffer'],
// As of Webpack 5, a new option called resolve.fullySpecified, was added.
// This option means that a full path, in particular to .mjs / .js files
// in ESM packages must have the full path of an import specified.
// Otherwise, compilation fails as this option defaults to true.
// This means we need to adjust our global injections to always
// resolve to include the full file extension if a file resolution is provided.
// @see https://github.com/cypress-io/cypress/issues/27599
// @see https://webpack.js.org/configuration/module/#resolvefullyspecified
// Due to Pnp compatibility issues, we want to make sure that we resolve to the 'process' library installed with the binary,
// which should resolve on leaf app/packages/server/node_modules/@cypress/webpack-batteries-included-preprocessor and up the tree.
// In other words, we want to resolve 'process' that is installed with cypress (or the package itself, i.e. @cypress/webpack-batteries-included-preprocessor)
// and not in the user's node_modules directory as it may not exist.
// @see https://github.com/cypress-io/cypress/issues/27947.
process: require.resolve('process/browser.js'),
}),
],
resolve: {
extensions: ['.js', '.json', '.jsx', '.mjs', '.coffee'],
fallback: {
assert: require.resolve('assert/'),
buffer: require.resolve('buffer/'),
child_process: false,
cluster: false,
console: false,
constants: require.resolve('constants-browserify'),
crypto: require.resolve('crypto-browserify'),
dgram: false,
dns: false,
domain: require.resolve('domain-browser'),
events: require.resolve('events/'),
fs: false,
http: require.resolve('stream-http'),
https: require.resolve('https-browserify'),
http2: false,
inspector: false,
module: false,
net: false,
os: require.resolve('os-browserify/browser'),
path: require.resolve('path-browserify'),
perf_hooks: false,
punycode: require.resolve('punycode/'),
process: require.resolve('process/browser.js'),
querystring: require.resolve('querystring-es3'),
readline: false,
repl: false,
stream: require.resolve('stream-browserify'),
string_decoder: require.resolve('string_decoder/'),
sys: require.resolve('util/'),
timers: require.resolve('timers-browserify'),
tls: false,
tty: require.resolve('tty-browserify'),
url: require.resolve('url/'),
util: require.resolve('util/'),
vm: require.resolve('vm-browserify'),
zlib: require.resolve('browserify-zlib'),
},
plugins: [],
},
}
}
const typescriptExtensionRegex = /\.tsx?$/
const preprocessor = (options = {}) => {
return (file) => {
if (!options.typescript && typescriptExtensionRegex.test(file.filePath)) {
return Promise.reject(new Error(`You are attempting to run a TypeScript file, but do not have TypeScript installed. Ensure you have 'typescript' installed to enable TypeScript support.\n\nThe file: ${file.filePath}`))
}
options.webpackOptions = options.webpackOptions || getDefaultWebpackOptions()
if (options.typescript) {
options = addTypeScriptConfig(file, options)
}
return webpackPreprocessor(options)(file)
}
}
preprocessor.defaultOptions = {
webpackOptions: getDefaultWebpackOptions(),
watchOptions: {},
}
preprocessor.getFullWebpackOptions = (filePath, typescript) => {
const webpackOptions = getDefaultWebpackOptions()
if (typescript) {
return addTypeScriptConfig({ filePath }, { typescript, webpackOptions }).webpackOptions
}
return webpackOptions
}
// for testing purposes, but do not add this to the typescript interface
preprocessor.__reset = webpackPreprocessor.__reset
module.exports = preprocessor