forked from vitejs/vite
-
Notifications
You must be signed in to change notification settings - Fork 0
/
serve.js
108 lines (98 loc) · 2.57 KB
/
serve.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
// @ts-check
// this is automtically detected by scripts/jestPerTestSetup.ts and will replace
// the default e2e test serve behavior
const path = require('path')
const http = require('http')
const sirv = require('sirv')
const fs = require('fs')
const port = (exports.port = 9527)
/**
* @param {string} root
* @param {boolean} isBuildTest
*/
exports.serve = async function serve(root, isBuildTest) {
const testDist = path.resolve(__dirname, '../moduleA/dist')
if (fs.existsSync(testDist)) {
emptyDir(testDist)
} else {
fs.mkdirSync(testDist, { recursive: true })
}
fs.symlinkSync(
path.resolve(testDist, '../src/index.js'),
path.resolve(testDist, 'symlinks-moduleA.esm.js')
)
if (!isBuildTest) {
const { createServer } = require('vite')
process.env.VITE_INLINE = 'inline-serve'
let viteServer = await (
await createServer({
root: root,
logLevel: 'silent',
server: {
watch: {
usePolling: true,
interval: 100
},
host: true,
fs: {
strict: !isBuildTest
}
},
build: {
target: 'esnext'
}
})
).listen()
// use resolved port/base from server
const base = viteServer.config.base === '/' ? '' : viteServer.config.base
const url =
(global.viteTestUrl = `http://localhost:${viteServer.config.server.port}${base}`)
await page.goto(url)
return viteServer
} else {
const { build } = require('vite')
await build({
root,
logLevel: 'silent',
configFile: path.resolve(__dirname, '../vite.config.js')
})
// start static file server
const serve = sirv(path.resolve(root, 'dist'))
const httpServer = http.createServer((req, res) => {
if (req.url === '/ping') {
res.statusCode = 200
res.end('pong')
} else {
serve(req, res)
}
})
return new Promise((resolve, reject) => {
try {
const server = httpServer.listen(port, async () => {
await page.goto(`http://localhost:${port}`)
resolve({
// for test teardown
async close() {
await new Promise((resolve) => {
server.close(resolve)
})
}
})
})
} catch (e) {
reject(e)
}
})
}
}
function emptyDir(dir) {
for (const file of fs.readdirSync(dir)) {
const abs = path.resolve(dir, file)
if (fs.lstatSync(abs).isDirectory()) {
emptyDir(abs)
fs.rmdirSync(abs)
} else {
fs.unlinkSync(abs)
}
}
}