Skip to content

Instantly share code, notes, and snippets.

@fusionstrings
Last active May 11, 2022 22:16
Show Gist options
  • Save fusionstrings/7c34f250919e112038234922761f8d95 to your computer and use it in GitHub Desktop.
Save fusionstrings/7c34f250919e112038234922761f8d95 to your computer and use it in GitHub Desktop.
chomp script to auto generate export map
version = 0.1
default-task = 'build'
extensions = ['[email protected]:swc', '[email protected]:jspm', '[email protected]:npm']
[template-options.npm]
auto-install = true
[[task]]
name = 'generate-exportmap'
deps = ['package.json', 'npm:install']
invalidation = 'always'
engine = 'node'
run = '''
import './exportmap-generator.js';
'''
import { Generator } from "@jspm/generator";
import { readFile, writeFile } from "fs/promises";
import mkdirp from "mkdirp";
import { dirname, parse } from "path";
mkdirp.sync(dirname(process.env.TARGET));
const { dir: CURRENT_DIRECTORY } = parse(import.meta.url);
const OUTPUT_DIR = "lib";
const DEST_PREFIX = `${CURRENT_DIRECTORY}/${OUTPUT_DIR}`;
const packageJSON = await readFile("package.json", "utf-8");
const parsedPackageJSON = JSON.parse(packageJSON);
const { exports } = parsedPackageJSON;
const generator = new Generator({
env: ["browser", "production"],
});
const dependencyMap = await generator.traceInstall("@jspm/packages");
const { staticDeps, dynamicDeps } = dependencyMap;
[...staticDeps, ...dynamicDeps].filter((dependency) =>
dependency.startsWith(CURRENT_DIRECTORY)
).sort().forEach((dependency) => {
const { ext } = parse(dependency);
const modulePath = dependency.replace(CURRENT_DIRECTORY, ".");
const subpath = dependency.replace(DEST_PREFIX, ".");
const exportPath = subpath.slice(0, subpath.length - ext.length);
exports[exportPath] = {
...exports[exportPath],
"browser": modulePath,
};
});
const sortedExports = {};
Object.keys(exports).sort().forEach((key) => {
sortedExports[key] = exports[key];
});
await writeFile(
'package.json',
JSON.stringify({ ...parsedPackageJSON, exports: sortedExports }, null, 2),
);
@fusionstrings
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment