forked from FredKSchott/snowpack
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathplugin.js
55 lines (52 loc) · 1.7 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
const workerpool = require('workerpool');
let worker, pool;
module.exports = function plugin(snowpackConfig, options = {}) {
// options validation
if (options) {
if (typeof options !== 'object') throw new Error(`options isn’t an object. Please see README.`);
if (options.input && !Array.isArray(options.input))
throw new Error(
`options.input must be an array (e.g. ['.js', '.mjs', '.jsx', '.ts', '.tsx'])`,
);
if (options.input && !options.input.length)
throw new Error(`options.input must specify at least one filetype`);
}
return {
name: '@snowpack/plugin-babel',
resolve: {
input: options.input || ['.js', '.mjs', '.jsx', '.ts', '.tsx'],
output: ['.js'], // always export JS
},
async load({filePath}) {
if (!filePath) {
return;
}
pool = pool || workerpool.pool(require.resolve('./worker.js'));
worker = worker || (await pool.proxy());
let encodedResult = await worker.transformFileAsync(filePath, {
cwd: process.cwd(),
ast: false,
compact: false,
sourceMaps: snowpackConfig.buildOptions.sourceMaps,
...(options.transformOptions || {}),
});
let {code, map} = JSON.parse(encodedResult);
if (code) {
// Some Babel plugins assume process.env exists, but Snowpack
// uses import.meta.env instead. Handle this here since it
// seems to be pretty common.
// See: https://www.pika.dev/npm/snowpack/discuss/496
code = code.replace(/process\.env/g, 'import.meta.env');
}
return {
'.js': {
code,
map,
},
};
},
cleanup() {
pool && pool.terminate();
},
};
};