| 22 | ` |
| 23 | |
| 24 | export async function createServer( |
| 25 | root = process.cwd(), |
| 26 | hmrPort, |
| 27 | customLogger, |
| 28 | ) { |
| 29 | const resolve = (p) => path.resolve(import.meta.dirname, p) |
| 30 | |
| 31 | const app = express() |
| 32 | |
| 33 | /** |
| 34 | * @type {import('vite').ViteDevServer} |
| 35 | */ |
| 36 | const vite = await ( |
| 37 | await import('vite') |
| 38 | ).createServer({ |
| 39 | root, |
| 40 | logLevel: isTest ? 'error' : 'info', |
| 41 | server: { |
| 42 | middlewareMode: true, |
| 43 | watch: { |
| 44 | // During tests we edit the files too fast and sometimes chokidar |
| 45 | // misses change events, so enforce polling for consistency |
| 46 | usePolling: true, |
| 47 | interval: 100, |
| 48 | }, |
| 49 | hmr: { |
| 50 | port: hmrPort, |
| 51 | }, |
| 52 | }, |
| 53 | appType: 'custom', |
| 54 | customLogger, |
| 55 | plugins: [ |
| 56 | { |
| 57 | name: 'virtual-file', |
| 58 | resolveId(id) { |
| 59 | if (id === 'virtual:file') { |
| 60 | return '\0virtual:file' |
| 61 | } |
| 62 | }, |
| 63 | load(id) { |
| 64 | if (id === '\0virtual:file') { |
| 65 | return 'import { virtual } from "/src/importedVirtual.js"; export { virtual };' |
| 66 | } |
| 67 | }, |
| 68 | }, |
| 69 | ], |
| 70 | }) |
| 71 | // use vite's connect instance as middleware |
| 72 | app.use(vite.middlewares) |
| 73 | |
| 74 | app.use('*all', async (req, res, next) => { |
| 75 | try { |
| 76 | let [url] = req.originalUrl.split('?') |
| 77 | |
| 78 | if (url === '/trailing-slash/dir/') { |
| 79 | const template = fs.readFileSync(resolve(`.${url}index.html`), 'utf-8') |
| 80 | const html = await vite.transformIndexHtml(url, template) |
| 81 | return res.status(200).set({ 'Content-Type': 'text/html' }).end(html) |