-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathdynamicImport.ts
More file actions
30 lines (28 loc) · 1.25 KB
/
dynamicImport.ts
File metadata and controls
30 lines (28 loc) · 1.25 KB
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
import {pathToFileURL} from 'url'
// - this exists because it looks like there's no straight-forward
// way to mock the dynamic import function, so mocking this instead
// (also, if it _is_ possible to mock the dynamic import,
// there's the risk of altering/breaking the behavior of imports
// across the board - including non-dynamic imports)
//
// - also, vitest has a limitation on mocking:
// https://vitest.dev/guide/mocking/modules.html#mocking-modules-pitfalls
//
// - basically if a function is called by another function in the same file
// it can't be mocked. So this was extracted into a separate file
//
// - one thing to note is vitest does the same thing here:
// https://github.com/vitest-dev/vitest/blob/main/test/core/src/dynamic-import.ts
// - and uses that with tests here:
// https://github.com/vitest-dev/vitest/blob/main/test/core/test/mock-internals.test.ts#L27
//
// - so this looks like a reasonable approach
export function dynamicImport(path: string) {
// - this if condition is for non-file imports.
// - this can be encountered when using esbuild to compile TS plugin files
// at run-time.
if (path.startsWith('data:') || path.startsWith('file:')) {
return import(path)
}
return import(pathToFileURL(path).href)
}