-
Notifications
You must be signed in to change notification settings - Fork 10
/
index.js
96 lines (85 loc) · 2.6 KB
/
index.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
/*
*
* Detects and fully resolves import requests for CommonJS files in node_modules.
*
*/
const commonjs = require('@rollup/plugin-commonjs');
const fs = require('fs');
const path = require('path');
const { parse } = require('cjs-module-lexer');
const { ResourceInterface } = require('@greenwood/cli/src/lib/resource-interface');
const rollupStream = require('@rollup/stream');
// bit of a workaround for now, but maybe this could be supported by cjs-module-lexar natively?
// https://github.com/guybedford/cjs-module-lexer/issues/35
const testForCjsModule = async(url) => {
let isCommonJs = false;
if (path.extname(url) === '.js' && (/node_modules/).test(url) && url.indexOf('es-module-shims.js') < 0) {
try {
const body = await fs.promises.readFile(url, 'utf-8');
await parse(body);
isCommonJs = true;
} catch (e) {
const { message } = e;
const isProbablyLexarErrorSoIgnore = message.indexOf('Unexpected import statement in CJS module.') >= 0
|| message.indexOf('Unexpected export statement in CJS module.') >= 0;
if (!isProbablyLexarErrorSoIgnore) {
// we probably _shouldn't_ ignore this, so let's log it since we don't want to swallow all errors
console.error(e);
}
}
}
return Promise.resolve(isCommonJs);
};
class ImportCommonJsResource extends ResourceInterface {
constructor(compilation, options) {
super(compilation, options);
}
async shouldIntercept(url) {
return new Promise(async (resolve, reject) => {
try {
const isCommonJs = await testForCjsModule(url);
return resolve(isCommonJs);
} catch (e) {
console.error(e);
reject(e);
}
});
}
async intercept(url) {
return new Promise(async(resolve, reject) => {
try {
const options = {
input: url,
output: { format: 'esm' },
plugins: [
commonjs()
]
};
const stream = rollupStream(options);
let bundle = '';
stream.on('data', (data) => (bundle += data));
stream.on('end', () => {
console.debug(`proccessed module "${url}" as a CommonJS module type.`);
resolve({
body: bundle
});
});
} catch (e) {
reject(e);
}
});
}
}
module.exports = (options = {}) => {
return [{
type: 'resource',
name: 'plugin-import-commonjs:resource',
provider: (compilation) => new ImportCommonJsResource(compilation, options)
}, {
type: 'rollup',
name: 'plugin-import-commonjs:rollup',
provider: () => [
commonjs()
]
}];
};