-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathindex.js
More file actions
99 lines (87 loc) · 2.55 KB
/
Copy pathindex.js
File metadata and controls
99 lines (87 loc) · 2.55 KB
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
// @ts-nocheck
/*
*
* Detects and fully resolves import requests for CommonJS files in node_modules.
*
*/
import commonjs from "@rollup/plugin-commonjs";
import fs from "fs/promises";
import { parse, init } from "cjs-module-lexer";
import rollupStream from "@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) => {
const { pathname } = url;
let isCommonJs = false;
if (
pathname.split(".").pop() === ".js" &&
pathname.startsWith("/node_modules/") &&
pathname.indexOf("es-module-shims.js") < 0
) {
try {
await init();
const body = await fs.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 isCommonJs;
};
class ImportCommonJsResource {
constructor(compilation) {
this.compilation = compilation;
}
async shouldIntercept(url) {
return await testForCjsModule(url);
}
async intercept(url, request, response) {
const { pathname } = url;
return new Promise((resolve, reject) => {
try {
const options = {
input: pathname,
output: { format: "esm" },
plugins: [commonjs()],
};
const stream = rollupStream(options);
let bundle = "";
stream.on("data", (data) => (bundle += data));
stream.on("end", () => {
console.debug(`processed module "${pathname}" as a CommonJS module type.`);
resolve(
new Response(bundle, {
headers: response.headers,
}),
);
});
} catch (e) {
reject(e);
}
});
}
}
/** @type {import('./types/index.d.ts').ImportCommonJSPlugin} */
const greenwoodPluginImportCommonJs = () => {
return [
{
type: "resource",
name: "plugin-import-commonjs:resource",
provider: (compilation) => new ImportCommonJsResource(compilation),
},
{
type: "rollup",
name: "plugin-import-commonjs:rollup",
provider: () => [commonjs()],
},
];
};
export { greenwoodPluginImportCommonJs };