From 7ea98c1af06b236a639d636da158b02bdbbf14b5 Mon Sep 17 00:00:00 2001 From: Franck Royer Date: Thu, 16 Jun 2022 14:36:08 +1000 Subject: [PATCH] Script to add js extension to esm files --- build-scripts/fix-imports.js | 61 ++++++++++++++++++++++++++++++++++++ package.json | 2 +- 2 files changed, 62 insertions(+), 1 deletion(-) create mode 100644 build-scripts/fix-imports.js diff --git a/build-scripts/fix-imports.js b/build-scripts/fix-imports.js new file mode 100644 index 0000000000..dd36bc1246 --- /dev/null +++ b/build-scripts/fix-imports.js @@ -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("================"); diff --git a/package.json b/package.json index 789e4ecbdf..da6ed0d884 100644 --- a/package.json +++ b/package.json @@ -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",