/
plugin.js
70 lines (67 loc) · 2.19 KB
/
plugin.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
const {isTestFilePath} = require('@web/test-runner');
const snowpack = require('snowpack');
const path = require('path');
/**
* Checks whether the url is a virtual file served by @web/test-runner.
* @param {string} url
*/
function isTestRunnerFile(url) {
return url.startsWith('/__web-dev-server') || url.startsWith('/__web-test-runner');
}
module.exports = function () {
if (process.env.NODE_ENV !== 'test') {
throw new Error(`@snowpack/web-test-runner-plugin: NODE_ENV must === "test" to build files correctly.
To Resolve:
1. Set "process.env.NODE_ENV = 'test';" at the top of your web-test-runner.config.js file (before all imports).
2. Prefix your web-test-runner CLI command: "NODE_ENV=test web-test-runner ...".
`);
}
let server, config;
return {
name: 'snowpack-plugin',
async serverStart({fileWatcher}) {
config = await snowpack.loadConfiguration({
packageOptions: {external: ['/__web-dev-server__web-socket.js']},
devOptions: {open: 'none', output: 'stream', hmr: false},
});
// npm packages should be installed/prepared ahead of time.
console.log('[snowpack] starting server...');
fileWatcher.add(Object.keys(config.mount));
server = await snowpack.startServer({
config,
lockfile: null,
});
},
async serverStop() {
return server.shutdown();
},
async serve({request}) {
if (isTestRunnerFile(request.url)) {
return;
}
const reqPath = request.path;
try {
const result = await server.loadUrl(reqPath, {isSSR: false});
return {body: result.contents, type: result.contentType};
} catch {
return;
}
},
transformImport({source}) {
if (!isTestFilePath(source) || isTestRunnerFile(source)) {
return;
}
// PERF(fks): https://github.com/snowpackjs/snowpack/pull/1259/files#r502963818
const reqPath = source.substring(
0,
source.indexOf('?') === -1 ? undefined : source.indexOf('?'),
);
const sourcePath = path.join(config.root || process.cwd(), reqPath);
try {
return snowpack.getUrlForFile(sourcePath, config);
} catch {
return;
}
},
};
};