Script to add js extension to esm files

This commit is contained in:
Franck Royer 2022-06-16 14:36:08 +10:00
parent 58006e1e38
commit 7ea98c1af0
No known key found for this signature in database
GPG Key ID: A82ED75A8DFC50A4
2 changed files with 62 additions and 1 deletions

View File

@ -0,0 +1,61 @@
import path from "path";
import fs from "fs";
const START_PATH = path.join(process.cwd(), "dist/esm");
const IMPORT_REGEXP =
/^((import|export) [^';]* from "(@[^";]+\/)?([^@";]*\/[^";]*)[^";]*)"/g;
const JUST_ADD_AN_EXTENSION = '$1.js"';
const ADD_INDEX_FILE = '$1/index.js"';
const JS_EXT = ".js";
function fixImportsAtFolder(rootPath) {
const entries = fs.readdirSync(rootPath);
entries.forEach((entry) => {
const entryPath = path.join(rootPath, entry);
if (entry.endsWith(JS_EXT)) {
fixImportsAtFile(entryPath);
} else {
const extName = path.extname(entry);
if (!extName) {
const stat = fs.statSync(entryPath);
if (stat.isDirectory()) {
fixImportsAtFolder(entryPath);
}
}
}
});
}
function fixImportsAtFile(filePath) {
const content = fs.readFileSync(filePath).toString("utf8");
const lines = content.split("\n");
const fixedLines = lines.map((l) => {
if (!l.match(IMPORT_REGEXP)) {
return l;
}
const [_, importPath] = l.split(`"`);
const fullPath = path.join(filePath, "..", importPath);
const exists = fs.existsSync(fullPath);
if (exists === false) {
console.log("Update ", l);
return l.replace(IMPORT_REGEXP, JUST_ADD_AN_EXTENSION);
}
const stat = fs.statSync(fullPath);
const isDirectory = stat.isDirectory();
if (isDirectory === true) {
console.log("Update ", l);
return l.replace(IMPORT_REGEXP, ADD_INDEX_FILE);
}
return l;
});
const withFixedImports = fixedLines.join("\n");
fs.writeFileSync(filePath, withFixedImports);
}
fixImportsAtFolder(START_PATH);
console.log("imports fixed...");
console.log("================");

View File

@ -23,7 +23,7 @@
"scripts": {
"prepare": "husky install",
"build": "rimraf ./dist; run-s build:**",
"build:esm": "tsc",
"build:esm": "tsc && node build-scripts/fix-imports.js",
"build:umd": "rollup --config rollup.config.js -- dist/esm/index.js",
"build:umd:min": "terser --ecma 6 --compress --mangle -o dist/umd/index.min.js -- dist/umd/index.js && gzip -9 -c dist/umd/index.min.js > dist/umd/index.min.js.gz",
"size": "npm run build:esm && size-limit",