@wrench/roll-typescript
Version:
plugin for bundling TypeScript with support of modular output and declaration bundle
61 lines (59 loc) • 2.1 kB
JavaScript
import { __awaiter } from "tslib";
import { bundleDts } from "./bundle-dts";
import { addFileNames, collectDependencies } from "./host";
import { Project } from "./project";
import { isOutputChunkWithId, lazy } from "./util";
const NAME = "@wrench/typescript-dts";
const NULL_NAME = `\0${NAME}`;
const EXPORT_NULL = "exports = null;";
export function typescriptDts(options) {
options = Object.assign({}, options);
let entry;
let project;
return {
name: NAME,
options(input) {
if (typeof input.input === "string")
entry = input.input;
else
throw new Error("input should be a single file!");
return null;
},
buildStart(input) {
project = lazy(this, "project", createProject, options);
const dependencies = collectDependencies(project, input.input);
addFileNames(project, dependencies);
},
resolveId(specifier, importer) {
ensureDeclarationFileName(importer || specifier);
return NULL_NAME;
},
load(id) {
return __awaiter(this, void 0, void 0, function* () {
if (id === NULL_NAME)
return EXPORT_NULL;
});
},
generateBundle(output, bundle) {
for (const key of Object.keys(bundle))
if (isOutputChunkWithId(bundle[key], NULL_NAME))
delete bundle[key];
bundleDts({
entry,
program: project.getProgram(),
output: output.file,
});
},
};
}
function ensureDeclarationFileName(fileName) {
if (!fileName.endsWith(".d.ts"))
throw new Error("should only contain '.d.ts.' files, but found: " + fileName);
}
function createProject(options) {
const ts = options.typescript || require("typescript");
return new Project({
ts,
options: Object.assign(Object.assign({}, ts.getDefaultCompilerOptions()), { allowJs: false, sourceMap: false, declaration: true }),
});
}