-
Notifications
You must be signed in to change notification settings - Fork 11
/
index.ts
104 lines (91 loc) · 2.73 KB
/
index.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
import path from 'path'
import Debug from 'debug'
import { build, InlineConfig } from 'vite'
import chokidar from 'chokidar'
type FileObject = Cypress.FileObject
type CypressPreprocessor = (file: FileObject) => Promise<string>
const debug = Debug('cypress-vite')
const watchers: Record<string, chokidar.FSWatcher> = {}
/**
* Cypress preprocessor for running e2e tests using vite.
*
* @param {InlineConfig | string} config - Vite config object, or path to user
* Vite config file for backwards compatibility
* @example
* setupNodeEvents(on) {
* on(
* 'file:preprocessor',
* vitePreprocessor(path.resolve(__dirname, './vite.config.ts')),
* )
* },
*/
function vitePreprocessor(
userConfig?: InlineConfig | string,
): CypressPreprocessor {
const config: InlineConfig =
typeof userConfig === 'string'
? { configFile: userConfig }
: userConfig ?? {}
debug('User config path: %s', config.configFile)
return async (file) => {
const { outputPath, filePath, shouldWatch } = file
debug('Preprocessing file %s', filePath)
const fileName = path.basename(outputPath)
const filenameWithoutExtension = path.basename(
outputPath,
path.extname(outputPath),
)
if (shouldWatch && !watchers[filePath]) {
// Watch this spec file if we are not already doing so (and Cypress is
// not in headless mode)
let initial = true
watchers[filePath] = chokidar.watch(filePath)
debug('Watcher for file %s cached', filePath)
file.on('close', async () => {
await watchers[filePath].close()
delete watchers[filePath]
debug('File %s closed.', filePath)
})
watchers[filePath].on('all', () => {
// Re-run the preprocessor if the file changes
if (!initial) {
file.emit('rerun')
}
initial = false
})
}
const defaultConfig: InlineConfig = {
logLevel: 'warn',
define: {
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV),
},
build: {
emptyOutDir: false,
minify: false,
outDir: path.dirname(outputPath),
sourcemap: true,
write: true,
watch: null,
lib: {
entry: filePath,
fileName: () => fileName,
formats: ['umd'],
name: filenameWithoutExtension,
},
rollupOptions: {
output: {
// override any manualChunks from the user config because they don't work with UMD
// eslint-disable-next-line @typescript-eslint/no-explicit-any
manualChunks: false as any,
},
},
},
}
await build({
...config,
...defaultConfig,
})
return outputPath
}
}
export default vitePreprocessor