72 lines
2.2 KiB
JavaScript
72 lines
2.2 KiB
JavaScript
// src/webpack/context.ts
|
|
import { resolve } from "path";
|
|
import { Buffer } from "buffer";
|
|
import sources from "webpack-sources";
|
|
import { Parser } from "acorn";
|
|
function createContext(compilation) {
|
|
return {
|
|
parse(code, opts = {}) {
|
|
return Parser.parse(code, {
|
|
sourceType: "module",
|
|
ecmaVersion: "latest",
|
|
locations: true,
|
|
...opts
|
|
});
|
|
},
|
|
addWatchFile(id) {
|
|
(compilation.fileDependencies ?? compilation.compilationDependencies).add(
|
|
resolve(process.cwd(), id)
|
|
);
|
|
},
|
|
emitFile(emittedFile) {
|
|
const outFileName = emittedFile.fileName || emittedFile.name;
|
|
if (emittedFile.source && outFileName) {
|
|
compilation.emitAsset(
|
|
outFileName,
|
|
sources ? new sources.RawSource(
|
|
// @ts-expect-error types mismatch
|
|
typeof emittedFile.source === "string" ? emittedFile.source : Buffer.from(emittedFile.source)
|
|
) : {
|
|
source: () => emittedFile.source,
|
|
size: () => emittedFile.source.length
|
|
}
|
|
);
|
|
}
|
|
},
|
|
getWatchFiles() {
|
|
return Array.from(
|
|
compilation.fileDependencies ?? compilation.compilationDependencies
|
|
);
|
|
}
|
|
};
|
|
}
|
|
|
|
// src/webpack/loaders/transform.ts
|
|
async function transform(source, map) {
|
|
const callback = this.async();
|
|
let unpluginName;
|
|
if (typeof this.query === "string") {
|
|
const query = new URLSearchParams(this.query);
|
|
unpluginName = query.get("unpluginName");
|
|
} else {
|
|
unpluginName = this.query.unpluginName;
|
|
}
|
|
const plugin = this._compiler?.$unpluginContext[unpluginName];
|
|
if (!plugin?.transform)
|
|
return callback(null, source, map);
|
|
const context = {
|
|
error: (error) => this.emitError(typeof error === "string" ? new Error(error) : error),
|
|
warn: (error) => this.emitWarning(typeof error === "string" ? new Error(error) : error)
|
|
};
|
|
const res = await plugin.transform.call(Object.assign(this._compilation && createContext(this._compilation), context), source, this.resource);
|
|
if (res == null)
|
|
callback(null, source, map);
|
|
else if (typeof res !== "string")
|
|
callback(null, res.code, map == null ? map : res.map || map);
|
|
else
|
|
callback(null, res, map);
|
|
}
|
|
export {
|
|
transform as default
|
|
};
|