diff --git a/README.md b/README.md
index 2c069fc..bc99bef 100644
--- a/README.md
+++ b/README.md
@@ -1,96 +1,80 @@
# npmize
-This package tries to help you to make npm package without thinking about cjs and mjs module.
+This package simplifies creating npm packages that work seamlessly across browsers and Node.js environments by handling CommonJS (CJS) and ES modules (ESM) for you.
-## Features
+# Features
-- Zero Config.
-- Very very simple.
-- Very very lightweight.
-- This supports `typescript`.
-- **Compile** to `cjs` and `mjs` without any distraction.
-- Enables `__dirname` and `__filename` for `mjs`(EsModule).
-- Can work with **browser**, **node** everything related to JavaScript.
+- **TypeScript Support:** Compile TypeScript code with ease.
+- **Zero Configuration:** Get started without any complex setup.
+- **Universal Compatibility:** Works across browsers and Node.js.
+- **ESM and CJS Compilation:** Compiles code to both CJS and ESM formats.
+- **Simple and Lightweight:** Easy to use and maintains a small footprint.
+- **Path Conversion:** Converts TypeScript config paths to relative paths for compatibility.
+- **ESM `__dirname` and `__filename` Support:** Enables these variables for ESM compatibility.
-
-
-
+# Installation
----
+**Locally:**
-## Installation
-
-- with npm (globally)
-
-```shell
-npm i -g npmize
+```bash
+npm install -D npmize
```
-- with npm
-
-```shell
-npm i -D npmize
-```
+**Yarn:**
-- with yarn
-
-```shell
+```bash
yarn add -D npmize
```
-- with pnpm
+**pnpm:**
-```shell
+```bash
pnpm add -D npmize
```
-
-
----
-
-
+# Usage
-# Command Line Interface
-
-The interface for command-line usage is fairly simplistic at this stage, as seen in the following usage section.
-
-## Usage
-
-```shell
+```bash
npmize [options]
```
-## How to use?
+**Example:**
-Add the help flag to see what **functionality** are available.
+1. Initialize a new project:
-```shell
-npmize --help
-```
+ ```bash
+ npmize init project-name
+ ```
-### Example:
+2. Get help information:
-```shell
-npmize init project-name
-npmize --help
-npmize --help-usage
-```
-
-- _*This makes your project ready*_
+ ```bash
+ npmize --help
+ npmize --help-usage
+ ```
-
+
-## **Note:**
+## TypeScript Path Handling:
-- You should use --module=cjs with dev mode when working with packages for node because `__dirname` and `__filename` isn't supported in esmodule in dev mode
-- Do not use `VGhpcyBuYW1lIGlzIGFscmVhZHkgdXNlZCB0byBlbmFibGUgX19kaXJuYW1lIGFuZCBfX2ZpbGVuYW1lIDop` as a variable name in your top level code.
+If you use TypeScript paths, ensure `baseUrl` is set in your `tsconfig.json`. For files within a `src` directory, set `baseUrl` to `./src`.
- - If you want to know why! [`Base64`](https://www.base64decode.org) ... Hope you know.
+```json
+{
+ "compilerOptions": {
+ "baseUrl": "./src",
+ "outDir": "./dist",
+ "paths": { "@/*": ["./*"] }
+ },
+ "include": ["./src"]
+}
+```
-- If you don't star our github repo your wife will divorce you, Else if you don't have wife then you will never get her.
+# Notes
-
+- **Variable Naming:** Avoid using `VGhpcyBuYW1lIGlzIGFscmVhZHkgdXNlZCB0byBlbmFibGUgX19kaXJuYW1lIGFuZCBfX2ZpbGVuYW1lIDop` (encoded using Base64) as a top-level variable name.
----
+
+
-Made by [Nazmus Sayad](https://github.com/NazmusSayad) with ❤️.
+Made with ❤️ by [Nazmus Sayad](https://github.com/NazmusSayad).
diff --git a/package-lock.json b/package-lock.json
index bc06c21..9b561b7 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,26 +1,26 @@
{
"name": "npmize",
- "version": "1.0.11",
+ "version": "1.0.13",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "npmize",
- "version": "1.0.11",
+ "version": "1.0.13",
"license": "ISC",
"dependencies": {
- "@babel/parser": "^7.20.7",
+ "@babel/parser": "^7.25.6",
"ansi-colors": "^4.1.3",
"lskit": "^1.0.0",
- "noarg": "^3.0.18",
+ "noarg": "^3.1.0",
"shelljs": "^0.8.5",
- "typescript": "^5.3.3"
+ "typescript": "^5.6.2"
},
"bin": {
"npmize": "dist/index.js"
},
"devDependencies": {
- "@types/node": "^18.11.9",
+ "@types/node": "^18.19.50",
"@types/shelljs": "^0.8.15"
}
},
@@ -43,12 +43,12 @@
}
},
"node_modules/@babel/parser": {
- "version": "7.25.3",
- "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.25.3.tgz",
- "integrity": "sha512-iLTJKDbJ4hMvFPgQwwsVoxtHyWpKKPBrxkANrSYewDPaPpT5py5yeVkgPIJ7XYXhndxJpaA3PyALSXQ7u8e/Dw==",
+ "version": "7.25.6",
+ "resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.25.6.tgz",
+ "integrity": "sha512-trGdfBdbD0l1ZPmcJ83eNxB9rbEax4ALFTF7fN386TMYbeCQbyme5cOEXQhbGXKebwGaB/J52w1mrklMcbgy6Q==",
"license": "MIT",
"dependencies": {
- "@babel/types": "^7.25.2"
+ "@babel/types": "^7.25.6"
},
"bin": {
"parser": "bin/babel-parser.js"
@@ -58,9 +58,9 @@
}
},
"node_modules/@babel/types": {
- "version": "7.25.2",
- "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.25.2.tgz",
- "integrity": "sha512-YTnYtra7W9e6/oAZEHj0bJehPRUlLH9/fbpT5LfB0NhQXyALCRkRs3zH9v07IYhkgpqX6Z78FnuccZr/l4Fs4Q==",
+ "version": "7.25.6",
+ "resolved": "https://registry.npmjs.org/@babel/types/-/types-7.25.6.tgz",
+ "integrity": "sha512-/l42B1qxpG6RdfYf343Uw1vmDjeNhneUXtzhojE7pDgfpEypmRhI6j1kr17XCVv4Cgl9HdAiQY2x0GwKm7rWCw==",
"license": "MIT",
"dependencies": {
"@babel/helper-string-parser": "^7.24.8",
@@ -82,14 +82,14 @@
}
},
"node_modules/@inquirer/checkbox": {
- "version": "2.4.7",
- "resolved": "https://registry.npmjs.org/@inquirer/checkbox/-/checkbox-2.4.7.tgz",
- "integrity": "sha512-5YwCySyV1UEgqzz34gNsC38eKxRBtlRDpJLlKcRtTjlYA/yDKuc1rfw+hjw+2WJxbAZtaDPsRl5Zk7J14SBoBw==",
+ "version": "2.5.0",
+ "resolved": "https://registry.npmjs.org/@inquirer/checkbox/-/checkbox-2.5.0.tgz",
+ "integrity": "sha512-sMgdETOfi2dUHT8r7TT1BTKOwNvdDGFDXYWtQ2J69SvlYNntk9I/gJe7r5yvMwwsuKnYbuRs3pNhx4tgNck5aA==",
"license": "MIT",
"dependencies": {
- "@inquirer/core": "^9.0.10",
+ "@inquirer/core": "^9.1.0",
"@inquirer/figures": "^1.0.5",
- "@inquirer/type": "^1.5.2",
+ "@inquirer/type": "^1.5.3",
"ansi-escapes": "^4.3.2",
"yoctocolors-cjs": "^2.1.2"
},
@@ -98,28 +98,28 @@
}
},
"node_modules/@inquirer/confirm": {
- "version": "3.1.22",
- "resolved": "https://registry.npmjs.org/@inquirer/confirm/-/confirm-3.1.22.tgz",
- "integrity": "sha512-gsAKIOWBm2Q87CDfs9fEo7wJT3fwWIJfnDGMn9Qy74gBnNFOACDNfhUzovubbJjWnKLGBln7/NcSmZwj5DuEXg==",
+ "version": "3.2.0",
+ "resolved": "https://registry.npmjs.org/@inquirer/confirm/-/confirm-3.2.0.tgz",
+ "integrity": "sha512-oOIwPs0Dvq5220Z8lGL/6LHRTEr9TgLHmiI99Rj1PJ1p1czTys+olrgBqZk4E2qC0YTzeHprxSQmoHioVdJ7Lw==",
"license": "MIT",
"dependencies": {
- "@inquirer/core": "^9.0.10",
- "@inquirer/type": "^1.5.2"
+ "@inquirer/core": "^9.1.0",
+ "@inquirer/type": "^1.5.3"
},
"engines": {
"node": ">=18"
}
},
"node_modules/@inquirer/core": {
- "version": "9.0.10",
- "resolved": "https://registry.npmjs.org/@inquirer/core/-/core-9.0.10.tgz",
- "integrity": "sha512-TdESOKSVwf6+YWDz8GhS6nKscwzkIyakEzCLJ5Vh6O3Co2ClhCJ0A4MG909MUWfaWdpJm7DE45ii51/2Kat9tA==",
+ "version": "9.1.0",
+ "resolved": "https://registry.npmjs.org/@inquirer/core/-/core-9.1.0.tgz",
+ "integrity": "sha512-RZVfH//2ytTjmaBIzeKT1zefcQZzuruwkpTwwbe/i2jTl4o9M+iML5ChULzz6iw1Ok8iUBBsRCjY2IEbD8Ft4w==",
"license": "MIT",
"dependencies": {
"@inquirer/figures": "^1.0.5",
- "@inquirer/type": "^1.5.2",
+ "@inquirer/type": "^1.5.3",
"@types/mute-stream": "^0.0.4",
- "@types/node": "^22.1.0",
+ "@types/node": "^22.5.2",
"@types/wrap-ansi": "^3.0.0",
"ansi-escapes": "^4.3.2",
"cli-spinners": "^2.9.2",
@@ -135,9 +135,9 @@
}
},
"node_modules/@inquirer/core/node_modules/@types/node": {
- "version": "22.4.2",
- "resolved": "https://registry.npmjs.org/@types/node/-/node-22.4.2.tgz",
- "integrity": "sha512-nAvM3Ey230/XzxtyDcJ+VjvlzpzoHwLsF7JaDRfoI0ytO0mVheerNmM45CtA0yOILXwXXxOrcUWH3wltX+7PSw==",
+ "version": "22.5.4",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-22.5.4.tgz",
+ "integrity": "sha512-FDuKUJQm/ju9fT/SeX/6+gBzoPzlVCzfzmGkwKvRHQVxi4BntVbyIwf6a4Xn62mrvndLiml6z/UBXIdEVjQLXg==",
"license": "MIT",
"dependencies": {
"undici-types": "~6.19.2"
@@ -150,13 +150,13 @@
"license": "MIT"
},
"node_modules/@inquirer/editor": {
- "version": "2.1.22",
- "resolved": "https://registry.npmjs.org/@inquirer/editor/-/editor-2.1.22.tgz",
- "integrity": "sha512-K1QwTu7GCK+nKOVRBp5HY9jt3DXOfPGPr6WRDrPImkcJRelG9UTx2cAtK1liXmibRrzJlTWOwqgWT3k2XnS62w==",
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/@inquirer/editor/-/editor-2.2.0.tgz",
+ "integrity": "sha512-9KHOpJ+dIL5SZli8lJ6xdaYLPPzB8xB9GZItg39MBybzhxA16vxmszmQFrRwbOA918WA2rvu8xhDEg/p6LXKbw==",
"license": "MIT",
"dependencies": {
- "@inquirer/core": "^9.0.10",
- "@inquirer/type": "^1.5.2",
+ "@inquirer/core": "^9.1.0",
+ "@inquirer/type": "^1.5.3",
"external-editor": "^3.1.0"
},
"engines": {
@@ -164,13 +164,13 @@
}
},
"node_modules/@inquirer/expand": {
- "version": "2.1.22",
- "resolved": "https://registry.npmjs.org/@inquirer/expand/-/expand-2.1.22.tgz",
- "integrity": "sha512-wTZOBkzH+ItPuZ3ZPa9lynBsdMp6kQ9zbjVPYEtSBG7UulGjg2kQiAnUjgyG4SlntpTce5bOmXAPvE4sguXjpA==",
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/@inquirer/expand/-/expand-2.3.0.tgz",
+ "integrity": "sha512-qnJsUcOGCSG1e5DTOErmv2BPQqrtT6uzqn1vI/aYGiPKq+FgslGZmtdnXbhuI7IlT7OByDoEEqdnhUnVR2hhLw==",
"license": "MIT",
"dependencies": {
- "@inquirer/core": "^9.0.10",
- "@inquirer/type": "^1.5.2",
+ "@inquirer/core": "^9.1.0",
+ "@inquirer/type": "^1.5.3",
"yoctocolors-cjs": "^2.1.2"
},
"engines": {
@@ -187,39 +187,39 @@
}
},
"node_modules/@inquirer/input": {
- "version": "2.2.9",
- "resolved": "https://registry.npmjs.org/@inquirer/input/-/input-2.2.9.tgz",
- "integrity": "sha512-7Z6N+uzkWM7+xsE+3rJdhdG/+mQgejOVqspoW+w0AbSZnL6nq5tGMEVASaYVWbkoSzecABWwmludO2evU3d31g==",
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/@inquirer/input/-/input-2.3.0.tgz",
+ "integrity": "sha512-XfnpCStx2xgh1LIRqPXrTNEEByqQWoxsWYzNRSEUxJ5c6EQlhMogJ3vHKu8aXuTacebtaZzMAHwEL0kAflKOBw==",
"license": "MIT",
"dependencies": {
- "@inquirer/core": "^9.0.10",
- "@inquirer/type": "^1.5.2"
+ "@inquirer/core": "^9.1.0",
+ "@inquirer/type": "^1.5.3"
},
"engines": {
"node": ">=18"
}
},
"node_modules/@inquirer/number": {
- "version": "1.0.10",
- "resolved": "https://registry.npmjs.org/@inquirer/number/-/number-1.0.10.tgz",
- "integrity": "sha512-kWTxRF8zHjQOn2TJs+XttLioBih6bdc5CcosXIzZsrTY383PXI35DuhIllZKu7CdXFi2rz2BWPN9l0dPsvrQOA==",
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/@inquirer/number/-/number-1.1.0.tgz",
+ "integrity": "sha512-ilUnia/GZUtfSZy3YEErXLJ2Sljo/mf9fiKc08n18DdwdmDbOzRcTv65H1jjDvlsAuvdFXf4Sa/aL7iw/NanVA==",
"license": "MIT",
"dependencies": {
- "@inquirer/core": "^9.0.10",
- "@inquirer/type": "^1.5.2"
+ "@inquirer/core": "^9.1.0",
+ "@inquirer/type": "^1.5.3"
},
"engines": {
"node": ">=18"
}
},
"node_modules/@inquirer/password": {
- "version": "2.1.22",
- "resolved": "https://registry.npmjs.org/@inquirer/password/-/password-2.1.22.tgz",
- "integrity": "sha512-5Fxt1L9vh3rAKqjYwqsjU4DZsEvY/2Gll+QkqR4yEpy6wvzLxdSgFhUcxfDAOtO4BEoTreWoznC0phagwLU5Kw==",
+ "version": "2.2.0",
+ "resolved": "https://registry.npmjs.org/@inquirer/password/-/password-2.2.0.tgz",
+ "integrity": "sha512-5otqIpgsPYIshqhgtEwSspBQE40etouR8VIxzpJkv9i0dVHIpyhiivbkH9/dGiMLdyamT54YRdGJLfl8TFnLHg==",
"license": "MIT",
"dependencies": {
- "@inquirer/core": "^9.0.10",
- "@inquirer/type": "^1.5.2",
+ "@inquirer/core": "^9.1.0",
+ "@inquirer/type": "^1.5.3",
"ansi-escapes": "^4.3.2"
},
"engines": {
@@ -227,34 +227,34 @@
}
},
"node_modules/@inquirer/prompts": {
- "version": "5.3.8",
- "resolved": "https://registry.npmjs.org/@inquirer/prompts/-/prompts-5.3.8.tgz",
- "integrity": "sha512-b2BudQY/Si4Y2a0PdZZL6BeJtl8llgeZa7U2j47aaJSCeAl1e4UI7y8a9bSkO3o/ZbZrgT5muy/34JbsjfIWxA==",
+ "version": "5.5.0",
+ "resolved": "https://registry.npmjs.org/@inquirer/prompts/-/prompts-5.5.0.tgz",
+ "integrity": "sha512-BHDeL0catgHdcHbSFFUddNzvx/imzJMft+tWDPwTm3hfu8/tApk1HrooNngB2Mb4qY+KaRWF+iZqoVUPeslEog==",
"license": "MIT",
"dependencies": {
- "@inquirer/checkbox": "^2.4.7",
- "@inquirer/confirm": "^3.1.22",
- "@inquirer/editor": "^2.1.22",
- "@inquirer/expand": "^2.1.22",
- "@inquirer/input": "^2.2.9",
- "@inquirer/number": "^1.0.10",
- "@inquirer/password": "^2.1.22",
- "@inquirer/rawlist": "^2.2.4",
- "@inquirer/search": "^1.0.7",
- "@inquirer/select": "^2.4.7"
+ "@inquirer/checkbox": "^2.5.0",
+ "@inquirer/confirm": "^3.2.0",
+ "@inquirer/editor": "^2.2.0",
+ "@inquirer/expand": "^2.3.0",
+ "@inquirer/input": "^2.3.0",
+ "@inquirer/number": "^1.1.0",
+ "@inquirer/password": "^2.2.0",
+ "@inquirer/rawlist": "^2.3.0",
+ "@inquirer/search": "^1.1.0",
+ "@inquirer/select": "^2.5.0"
},
"engines": {
"node": ">=18"
}
},
"node_modules/@inquirer/rawlist": {
- "version": "2.2.4",
- "resolved": "https://registry.npmjs.org/@inquirer/rawlist/-/rawlist-2.2.4.tgz",
- "integrity": "sha512-pb6w9pWrm7EfnYDgQObOurh2d2YH07+eDo3xQBsNAM2GRhliz6wFXGi1thKQ4bN6B0xDd6C3tBsjdr3obsCl3Q==",
+ "version": "2.3.0",
+ "resolved": "https://registry.npmjs.org/@inquirer/rawlist/-/rawlist-2.3.0.tgz",
+ "integrity": "sha512-zzfNuINhFF7OLAtGHfhwOW2TlYJyli7lOUoJUXw/uyklcwalV6WRXBXtFIicN8rTRK1XTiPWB4UY+YuW8dsnLQ==",
"license": "MIT",
"dependencies": {
- "@inquirer/core": "^9.0.10",
- "@inquirer/type": "^1.5.2",
+ "@inquirer/core": "^9.1.0",
+ "@inquirer/type": "^1.5.3",
"yoctocolors-cjs": "^2.1.2"
},
"engines": {
@@ -262,14 +262,14 @@
}
},
"node_modules/@inquirer/search": {
- "version": "1.0.7",
- "resolved": "https://registry.npmjs.org/@inquirer/search/-/search-1.0.7.tgz",
- "integrity": "sha512-p1wpV+3gd1eST/o5N3yQpYEdFNCzSP0Klrl+5bfD3cTTz8BGG6nf4Z07aBW0xjlKIj1Rp0y3x/X4cZYi6TfcLw==",
+ "version": "1.1.0",
+ "resolved": "https://registry.npmjs.org/@inquirer/search/-/search-1.1.0.tgz",
+ "integrity": "sha512-h+/5LSj51dx7hp5xOn4QFnUaKeARwUCLs6mIhtkJ0JYPBLmEYjdHSYh7I6GrLg9LwpJ3xeX0FZgAG1q0QdCpVQ==",
"license": "MIT",
"dependencies": {
- "@inquirer/core": "^9.0.10",
+ "@inquirer/core": "^9.1.0",
"@inquirer/figures": "^1.0.5",
- "@inquirer/type": "^1.5.2",
+ "@inquirer/type": "^1.5.3",
"yoctocolors-cjs": "^2.1.2"
},
"engines": {
@@ -277,14 +277,14 @@
}
},
"node_modules/@inquirer/select": {
- "version": "2.4.7",
- "resolved": "https://registry.npmjs.org/@inquirer/select/-/select-2.4.7.tgz",
- "integrity": "sha512-JH7XqPEkBpNWp3gPCqWqY8ECbyMoFcCZANlL6pV9hf59qK6dGmkOlx1ydyhY+KZ0c5X74+W6Mtp+nm2QX0/MAQ==",
+ "version": "2.5.0",
+ "resolved": "https://registry.npmjs.org/@inquirer/select/-/select-2.5.0.tgz",
+ "integrity": "sha512-YmDobTItPP3WcEI86GvPo+T2sRHkxxOq/kXmsBjHS5BVXUgvgZ5AfJjkvQvZr03T81NnI3KrrRuMzeuYUQRFOA==",
"license": "MIT",
"dependencies": {
- "@inquirer/core": "^9.0.10",
+ "@inquirer/core": "^9.1.0",
"@inquirer/figures": "^1.0.5",
- "@inquirer/type": "^1.5.2",
+ "@inquirer/type": "^1.5.3",
"ansi-escapes": "^4.3.2",
"yoctocolors-cjs": "^2.1.2"
},
@@ -293,9 +293,9 @@
}
},
"node_modules/@inquirer/type": {
- "version": "1.5.2",
- "resolved": "https://registry.npmjs.org/@inquirer/type/-/type-1.5.2.tgz",
- "integrity": "sha512-w9qFkumYDCNyDZmNQjf/n6qQuvQ4dMC3BJesY4oF+yr0CxR5vxujflAVeIcS6U336uzi9GM0kAfZlLrZ9UTkpA==",
+ "version": "1.5.3",
+ "resolved": "https://registry.npmjs.org/@inquirer/type/-/type-1.5.3.tgz",
+ "integrity": "sha512-xUQ14WQGR/HK5ei+2CvgcwoH9fQ4PgPGmVFSN0pc1+fVyDL3MREhyAY7nxEErSu6CkllBM3D7e3e+kOvtu+eIg==",
"license": "MIT",
"dependencies": {
"mute-stream": "^1.0.0"
@@ -332,9 +332,9 @@
}
},
"node_modules/@types/node": {
- "version": "18.19.45",
- "resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.45.tgz",
- "integrity": "sha512-VZxPKNNhjKmaC1SUYowuXSRSMGyQGmQjvvA1xE4QZ0xce2kLtEhPDS+kqpCPBZYgqblCLQ2DAjSzmgCM5auvhA==",
+ "version": "18.19.50",
+ "resolved": "https://registry.npmjs.org/@types/node/-/node-18.19.50.tgz",
+ "integrity": "sha512-xonK+NRrMBRtkL1hVCc3G+uXtjh1Al4opBLjqVmipe5ZAaBYWW6cNAiBVZ1BvmkBhep698rP3UM3aRAdSALuhg==",
"license": "MIT",
"dependencies": {
"undici-types": "~5.26.4"
@@ -594,9 +594,9 @@
}
},
"node_modules/is-core-module": {
- "version": "2.15.0",
- "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.15.0.tgz",
- "integrity": "sha512-Dd+Lb2/zvk9SKy1TGCt1wFJFo/MWBPMX5x7KcvLajWTGuomczdQX61PvY5yK6SVACwpoexWo81IfFyoKY2QnTA==",
+ "version": "2.15.1",
+ "resolved": "https://registry.npmjs.org/is-core-module/-/is-core-module-2.15.1.tgz",
+ "integrity": "sha512-z0vtXSwucUJtANQWldhbtbt7BnL0vxiFjIdDLAatwhDYty2bad6s+rijD6Ri4YuYJubLzIJLUidCh09e1djEVQ==",
"license": "MIT",
"dependencies": {
"hasown": "^2.0.2"
@@ -644,14 +644,13 @@
}
},
"node_modules/noarg": {
- "version": "3.0.18",
- "resolved": "https://registry.npmjs.org/noarg/-/noarg-3.0.18.tgz",
- "integrity": "sha512-m0/oNSuueBcjlia3PAvY/1nh1+4XajG4WXVgViaNBZBNDNd6fd7fXSsJnbut2fCViQFaFIb2iXUAesMJBD0T+Q==",
+ "version": "3.1.0",
+ "resolved": "https://registry.npmjs.org/noarg/-/noarg-3.1.0.tgz",
+ "integrity": "sha512-grnD4aCDBljJpm1qNlKuDAxWfEbHPP0zyJzcCecyM4g6bCxDoZ5KoBynZ+Ro6bEIFYPjna+Brp5ffnNI/sfHAg==",
"dependencies": {
"@inquirer/prompts": "^5.3.8",
"ansi-colors": "^4.1.3",
- "cli-table3": "^0.6.5",
- "utility-types": "^3.11.0"
+ "cli-table3": "^0.6.5"
}
},
"node_modules/once": {
@@ -822,9 +821,9 @@
}
},
"node_modules/typescript": {
- "version": "5.5.4",
- "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.5.4.tgz",
- "integrity": "sha512-Mtq29sKDAEYP7aljRgtPOpTvOfbwRWlS6dPRzwjdE+C0R4brX/GUyhHSecbHMFLNBLcJIPt9nl9yG5TZ1weH+Q==",
+ "version": "5.6.2",
+ "resolved": "https://registry.npmjs.org/typescript/-/typescript-5.6.2.tgz",
+ "integrity": "sha512-NW8ByodCSNCwZeghjN3o+JX5OFH0Ojg6sadjEKY4huZ52TqbJTJnDo5+Tw98lSy63NZvi4n+ez5m2u5d4PkZyw==",
"license": "Apache-2.0",
"bin": {
"tsc": "bin/tsc",
@@ -840,15 +839,6 @@
"integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==",
"license": "MIT"
},
- "node_modules/utility-types": {
- "version": "3.11.0",
- "resolved": "https://registry.npmjs.org/utility-types/-/utility-types-3.11.0.tgz",
- "integrity": "sha512-6Z7Ma2aVEWisaL6TvBCy7P8rm2LQoPv6dJ7ecIaIixHcwfbJ0x7mWdbcwlIM5IGQxPZSFYeqRCqlOOeKoJYMkw==",
- "license": "MIT",
- "engines": {
- "node": ">= 4"
- }
- },
"node_modules/wrap-ansi": {
"version": "6.2.0",
"resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-6.2.0.tgz",
diff --git a/package.json b/package.json
index 6d0968c..fbdff69 100644
--- a/package.json
+++ b/package.json
@@ -1,24 +1,24 @@
{
"name": "npmize",
"description": "Let's create an npm package without worrying about anything.",
- "version": "1.0.12",
+ "version": "1.0.13",
"bin": "./dist/index.js",
"scripts": {
"dev": "tsc -w",
"build": "node ./build.cjs",
- "lab": "nodemon ./src/__lab.ts"
+ "lab": "run ./src/__lab__/index.ts"
},
"type": "commonjs",
"dependencies": {
- "@babel/parser": "^7.20.7",
+ "@babel/parser": "^7.25.6",
"ansi-colors": "^4.1.3",
"lskit": "^1.0.0",
- "noarg": "^3.0.18",
+ "noarg": "^3.1.0",
"shelljs": "^0.8.5",
- "typescript": "^5.3.3"
+ "typescript": "^5.6.2"
},
"devDependencies": {
- "@types/node": "^18.11.9",
+ "@types/node": "^18.19.50",
"@types/shelljs": "^0.8.15"
},
"keywords": [
diff --git a/src/__lab.ts b/src/__lab.ts
deleted file mode 100644
index 768ad9a..0000000
--- a/src/__lab.ts
+++ /dev/null
@@ -1,7 +0,0 @@
-console.clear()
-
-import app from './main'
-
-app.start(['init', '../npmize-test'])
-// app.start(['dev', '../npmize-test'])
-// app.start(['build', '../npmize-test'])
diff --git a/src/__lab__/index.ts b/src/__lab__/index.ts
new file mode 100644
index 0000000..03a42b2
--- /dev/null
+++ b/src/__lab__/index.ts
@@ -0,0 +1,8 @@
+console.clear()
+
+import { app } from '../app'
+import '../main'
+
+// app.start(['init', '../npmize-test'])
+app.start(['dev', '../npmize-test', '--module', 'mjs'])
+// app.start(['build', '../npmize-test'])
diff --git a/src/app.ts b/src/app.ts
new file mode 100644
index 0000000..b6d65e1
--- /dev/null
+++ b/src/app.ts
@@ -0,0 +1,89 @@
+import NoArg from 'noarg'
+import config from './config'
+import { getVersion } from './utils'
+import ansiColors from 'ansi-colors'
+
+export const app = NoArg.create(config.name, {
+ description: config.description,
+ flags: {
+ version: NoArg.boolean().aliases('v').description('Show the version'),
+ },
+}).on((_, flags) => {
+ if (flags.version) {
+ console.log(getVersion())
+ } else app.renderHelp()
+})
+
+export const init = app.create('init', {
+ description: 'Initialize a new npm package',
+
+ arguments: [
+ {
+ name: 'name',
+ type: NoArg.string()
+ .description('Name of the package')
+ .ask("What's the name of the package?")
+ .default('.'),
+ },
+ ],
+
+ flags: {
+ pkg: NoArg.boolean().default(true).description("Write 'package.json'"),
+ install: NoArg.boolean().default(true).description('Install TypeScript'),
+ tsconfig: NoArg.boolean()
+ .default(true)
+ .description('Write "tsconfig.json"'),
+ demo: NoArg.boolean().default(true).description('Write a sample file'),
+ workflow: NoArg.boolean()
+ .default(true)
+ .description('Write a workflow file'),
+
+ ignore: NoArg.boolean()
+ .default(true)
+ .description("Write '.gitignore' and '.npmignore'"),
+ npmignore: NoArg.boolean().default(true).description("Write '.npmignore'"),
+ gitignore: NoArg.boolean().default(true).description("Write '.gitignore'"),
+ },
+})
+
+const devAndBuild = NoArg.defineConfig({
+ optionalArguments: [
+ {
+ name: 'root',
+ type: NoArg.string().description('Root directory'),
+ },
+ ],
+
+ flags: {
+ module: NoArg.string('cjs', 'mjs')
+ .aliases('m')
+ .description("Output module's type"),
+
+ node: NoArg.boolean()
+ .aliases('n')
+ .default(false)
+ .description('Enable __dirname and __filename in ES modules'),
+ },
+
+ trailingArguments: '--tsc',
+
+ notes: [
+ `Arguments after "${ansiColors.yellow(
+ '--tsc'
+ )}" will be passed to ${ansiColors.yellow('TypeScript')} compiler.`,
+
+ ['--project', '--module', '--outDir', '--watch']
+ .map((flag) => ansiColors.yellow(flag))
+ .join(', ') + ' and their aliases are ignored.',
+ ],
+})
+
+export const dev = app.create('dev', {
+ description: 'Start a development',
+ ...devAndBuild,
+})
+
+export const build = app.create('build', {
+ description: 'Build the package for production',
+ ...devAndBuild,
+})
diff --git a/src/config.ts b/src/config.ts
index 27d9f26..1656fab 100644
--- a/src/config.ts
+++ b/src/config.ts
@@ -1,7 +1,4 @@
export default {
name: 'npmize' as Lowercase,
description: 'A tool to help you publish your package to npm with ease',
- defaultOutDir: './dist',
- tempOutDir: './.npmize',
- ghWorkflowDir: './.github/workflows',
}
diff --git a/src/index.ts b/src/index.ts
index c76557e..93ff521 100644
--- a/src/index.ts
+++ b/src/index.ts
@@ -1,4 +1,5 @@
#!/usr/bin/env node
-import app from './main'
+import { app } from './app'
+import './main'
app.start()
diff --git a/src/main.ts b/src/main.ts
index 41637d2..8711fa6 100644
--- a/src/main.ts
+++ b/src/main.ts
@@ -1,147 +1,78 @@
import path from 'path'
-import config from './config'
+import * as app from './app'
import dev from './program/dev'
-import NoArg from 'noarg'
import init from './program/init'
import build from './program/build'
import { getVersion } from './utils'
import ansiColors from 'ansi-colors'
import { readTSConfig } from './scripts/tsconfig'
-const app = NoArg.create(config.name, {
- description: config.description,
- flags: {
- version: NoArg.boolean().aliases('v').description('Show the version'),
- },
-}).on((_, flags) => {
+app.app.on((_, flags) => {
if (flags.version) {
console.log(getVersion())
- } else app.renderHelp()
+ } else app.app.renderHelp()
})
-app
- .create('init', {
- description: 'Initialize a new npm package',
-
- arguments: [
- {
- name: 'name',
- type: NoArg.string()
- .description('Name of the package')
- .ask("What's the name of the package?")
- .default('.'),
- },
- ],
-
- flags: {
- pkg: NoArg.boolean().default(true).description("Write 'package.json'"),
- install: NoArg.boolean().default(true).description('Install TypeScript'),
- tsconfig: NoArg.boolean()
- .default(true)
- .description('Write "tsconfig.json"'),
- demo: NoArg.boolean().default(true).description('Write a sample file'),
- workflow: NoArg.boolean()
- .default(true)
- .description('Write a workflow file'),
-
- ignore: NoArg.boolean()
- .default(true)
- .description("Write '.gitignore' and '.npmignore'"),
- npmignore: NoArg.boolean()
- .default(true)
- .description("Write '.npmignore'"),
- gitignore: NoArg.boolean()
- .default(true)
- .description("Write '.gitignore'"),
- },
- })
- .on(([nameArg = '.'], flags) => {
- const root = path.resolve(nameArg)
-
- init(root, {
- writeSample: flags.demo,
- writePackageJSON: flags.pkg,
- installPackages: flags.install,
- writeGitIgnore: flags.ignore && flags.gitignore,
- writeNpmIgnore: flags.ignore && flags.npmignore,
- writeTSConfig: flags.tsconfig,
- ghWorkflow: flags.workflow,
- })
+app.init.on(([nameArg = '.'], flags) => {
+ const root = path.resolve(nameArg)
+
+ init(root, {
+ writeSample: flags.demo,
+ writePackageJSON: flags.pkg,
+ installPackages: flags.install,
+ writeGitIgnore: flags.ignore && flags.gitignore,
+ writeNpmIgnore: flags.ignore && flags.npmignore,
+ writeTSConfig: flags.tsconfig,
+ ghWorkflow: flags.workflow,
})
-
-const devAndBuild = NoArg.defineConfig({
- optionalArguments: [
- {
- name: 'root',
- type: NoArg.string().description('Root directory'),
- },
- ],
-
- flags: {
- module: NoArg.string('cjs', 'mjs')
- .aliases('m')
- .description("Output module's type"),
-
- outDir: NoArg.string().aliases('o').description('Output directory'),
-
- node: NoArg.boolean()
- .aliases('n')
- .default(false)
- .description('Enable __dirname and __filename in ES modules'),
- },
-
- config: {
- enableTrailingArgs: true,
- trailingArgsSeparator: '--tsc',
- },
-
- notes: [
- `Arguments after "${ansiColors.yellow(
- '--tsc'
- )}" will be passed to ${ansiColors.yellow('TypeScript')} compiler.`,
-
- ['--project', '--module', '--outDir', '--watch']
- .map((flag) => ansiColors.yellow(flag))
- .join(', ') + ' and their aliases are ignored.',
- ],
})
-app
- .create('dev', {
- description: 'Start a development',
- ...devAndBuild,
+app.dev.on(([rootArg = '.', railingArgs], options) => {
+ const rootPath = path.resolve(rootArg)
+ const tsConfig = readTSConfig(rootPath)
+
+ if (!tsConfig) {
+ return console.log(
+ ansiColors.bgRed(' ERROR: '),
+ 'Could not find "tsconfig.json"'
+ )
+ }
+
+ if (!tsConfig?.outDir) {
+ return console.log(
+ ansiColors.bgRed(' ERROR: '),
+ 'The "outDir" option is required in "tsconfig.json"'
+ )
+ }
+
+ dev(rootPath, {
+ ...options,
+ tsConfig,
+ tsc: railingArgs,
})
- .on(([rootArg = '.', railingArgs], options) => {
- const rootPath = path.resolve(rootArg)
- const tsConfig = readTSConfig(rootPath)
-
- dev(rootPath, {
- ...options,
- tsc: railingArgs,
- outDir: path.join(
- rootPath,
- options.outDir ?? tsConfig?.outDir ?? config.defaultOutDir
- ),
- })
- })
-
-app
- .create('build', {
- description: 'Build the package for production',
- ...devAndBuild,
- })
- .on(([rootArg = '.', railingArgs], options) => {
- const rootPath = path.resolve(rootArg)
- const tsConfig = readTSConfig(rootPath)
+})
- build(rootPath, {
- ...options,
- tsc: railingArgs,
- outDir: path.join(
- rootPath,
- options.outDir ?? tsConfig?.outDir ?? config.defaultOutDir
- ),
- })
+app.build.on(([rootArg = '.', railingArgs], options) => {
+ const rootPath = path.resolve(rootArg)
+ const tsConfig = readTSConfig(rootPath)
+
+ if (!tsConfig) {
+ return console.log(
+ ansiColors.bgRed(' ERROR: '),
+ 'Could not find "tsconfig.json"'
+ )
+ }
+
+ if (!tsConfig?.outDir) {
+ return console.log(
+ ansiColors.bgRed(' ERROR: '),
+ 'The "outDir" option is required in "tsconfig.json"'
+ )
+ }
+
+ build(rootPath, {
+ ...options,
+ tsConfig,
+ tsc: railingArgs,
})
-
-export default app
+})
diff --git a/src/program/build.ts b/src/program/build.ts
index f35deac..e88df28 100644
--- a/src/program/build.ts
+++ b/src/program/build.ts
@@ -1,44 +1,55 @@
import fs from 'fs'
+import path from 'path'
import * as lskit from 'lskit'
import tsc from '../scripts/tsc'
+import { CompileOptions } from './types.t'
import updateImports from '../updateImports'
import pushNodeCode from '../scripts/pushNodeCode'
import { cleanDir, getNodeModulesTempDir, moveFiles } from '../utils'
-export default function (basePath: string, options: Options) {
- console.log(`Build started at ${basePath}`)
+export default function (rootPath: string, options: CompileOptions) {
+ console.log(`Build started at ${rootPath}`)
console.log('')
- cleanDir(options.outDir)
+ const outDir = path.resolve(options.tsConfig?.outDir!)
+ cleanDir(outDir)
if (options.module) {
- runBuild(options.module, basePath, options)
+ runBuild(rootPath, outDir, options.module, options)
} else {
- runBuild('cjs', basePath, options)
- runBuild('mjs', basePath, options)
+ runBuild(rootPath, outDir, 'cjs', options)
+ runBuild(rootPath, outDir, 'mjs', options)
}
}
function runBuild(
- moduleType: Exclude,
- basePath: string,
- options: Omit
+ rootPath: string,
+ outDir: string,
+ moduleType: Exclude,
+ options: Omit
) {
console.log(`Building ${moduleType}...`)
- const tempDir = getNodeModulesTempDir(basePath)
- cleanDir(tempDir)
+ const tempOutDir = getNodeModulesTempDir(rootPath, 'build-' + moduleType)
+ cleanDir(tempOutDir)
- tsc(basePath, [
+ tsc(rootPath, [
...options.tsc,
- `--outDir ${tempDir}`,
+ `--outDir ${tempOutDir}`,
`--module ${moduleType === 'cjs' ? 'commonjs' : 'esnext'}`,
])
- const files = lskit.sync(tempDir)
- const updatedImports = updateImports(moduleType, files)
- const movedFiles = moveFiles(tempDir, options.outDir, updatedImports)
+ const files = lskit.sync(tempOutDir)
+ const updatedImports = updateImports(
+ rootPath,
+ tempOutDir,
+ options.tsConfig?.baseUrl,
+ options.tsConfig?.paths,
+ moduleType,
+ files
+ )
+ const movedFiles = moveFiles(tempOutDir, outDir, updatedImports)
if (moduleType === 'mjs' && options.node && movedFiles.length) {
console.log('Enabling Node.js __dirname and __filename...')
pushNodeCode(...movedFiles)
@@ -61,13 +72,6 @@ function runBuild(
).toFixed(2)}KB`
)
- cleanDir(tempDir, false)
+ cleanDir(tempOutDir, false)
console.log('')
}
-
-type Options = {
- tsc: string[]
- node: boolean
- outDir: string
- module?: 'cjs' | 'mjs'
-}
diff --git a/src/program/dev.ts b/src/program/dev.ts
index ea13941..76f89c7 100644
--- a/src/program/dev.ts
+++ b/src/program/dev.ts
@@ -1,47 +1,51 @@
import fs from 'fs'
import path from 'path'
import tsc from '../scripts/tsc'
+import { CompileOptions } from './types.t'
import updateImports from '../updateImports'
import pushNodeCode from '../scripts/pushNodeCode'
import { cleanDir, getNodeModulesTempDir, moveFiles } from '../utils'
-export default function (basePath: string, options: DevOptions) {
+export default function (rootPath: string, options: CompileOptions) {
options.module ??= 'cjs'
- const tempDir = getNodeModulesTempDir(basePath)
- cleanDir(tempDir)
- cleanDir(options.outDir)
+ const finalOutDir = path.resolve(options.tsConfig?.outDir!)
+ cleanDir(finalOutDir)
+
+ const tempOutDir = getNodeModulesTempDir(rootPath, 'dev-' + options.module)
+ cleanDir(tempOutDir)
function makeOutFiles(filename: string, outModule: 'cjs' | 'mjs') {
- const fullPath = path.join(tempDir, filename)
+ const fullPath = path.join(tempOutDir, filename)
if (fs.existsSync(fullPath) && fs.statSync(fullPath).isFile()) {
- const updatedImports = updateImports(outModule, [fullPath])
- const [movedFile] = moveFiles(tempDir, options.outDir, updatedImports)
+ const updatedImports = updateImports(
+ rootPath,
+ tempOutDir,
+ options.tsConfig?.baseUrl,
+ options.tsConfig?.paths,
+ outModule,
+ [fullPath]
+ )
+
+ const [movedFile] = moveFiles(tempOutDir, finalOutDir, updatedImports)
if (outModule === 'mjs' && options.node) pushNodeCode(movedFile)
}
}
- fs.watch(tempDir, { recursive: true }, (event, filename) => {
+ fs.watch(tempOutDir, { recursive: true }, (event, filename) => {
if (event !== 'change' || !filename) return
if (!(filename.endsWith('.js') || filename.endsWith('.ts'))) return
makeOutFiles(filename, options.module!)
})
tsc(
- basePath,
+ rootPath,
[
...options.tsc,
- `--outDir ${tempDir}`,
+ `--outDir ${tempOutDir}`,
`--module ${options.module === 'cjs' ? 'commonjs' : 'esnext'}`,
'--watch',
],
true
)
}
-
-type DevOptions = {
- module?: 'cjs' | 'mjs'
- node?: boolean
- outDir: string
- tsc: string[]
-}
diff --git a/src/program/init.ts b/src/program/init.ts
index 12fc4e4..f0fa59e 100644
--- a/src/program/init.ts
+++ b/src/program/init.ts
@@ -50,7 +50,8 @@ export default function (basePath: string, options: InitOptions) {
path.join(basePath, './tsconfig.json'),
{
compilerOptions: {
- baseUrl: '.',
+ baseUrl: './src',
+ outDir: './dist',
target: 'ES6' as any,
skipLibCheck: true,
@@ -61,6 +62,10 @@ export default function (basePath: string, options: InitOptions) {
strict: true,
pretty: true,
removeComments: true,
+
+ paths: {
+ '@/*': ['./*'],
+ },
},
include: ['./src'],
diff --git a/src/program/types.t.ts b/src/program/types.t.ts
new file mode 100644
index 0000000..fc8e158
--- /dev/null
+++ b/src/program/types.t.ts
@@ -0,0 +1,8 @@
+import { readTSConfig } from '../scripts/tsconfig'
+
+export type CompileOptions = {
+ tsc: string[]
+ node: boolean
+ module?: 'cjs' | 'mjs'
+ tsConfig: ReturnType
+}
diff --git a/src/scripts/ghWorkflows.ts b/src/scripts/ghWorkflows.ts
index 931d2b1..019b8c2 100644
--- a/src/scripts/ghWorkflows.ts
+++ b/src/scripts/ghWorkflows.ts
@@ -1,6 +1,5 @@
import fs from 'fs'
import path from 'path'
-import config from '../config'
import ansiColors from 'ansi-colors'
import { confirmDir, getNodeVersion } from '../utils'
@@ -46,7 +45,7 @@ jobs:
}
export default function (baseDir: string) {
- const workflowDir = confirmDir(baseDir, config.ghWorkflowDir)
+ const workflowDir = confirmDir(baseDir, './.github/workflows')
const publishWorkflowPath = path.join(workflowDir, 'npm-publish.yml')
fs.writeFileSync(
diff --git a/src/scripts/packageJSON.ts b/src/scripts/packageJSON.ts
index 649e477..1535f0e 100644
--- a/src/scripts/packageJSON.ts
+++ b/src/scripts/packageJSON.ts
@@ -1,5 +1,5 @@
import * as fs from 'fs'
-import path from 'path'
+import * as path from 'path'
import { writeFileSync } from '../utils'
function read(basePath: string): Record {
diff --git a/src/scripts/tsconfig.ts b/src/scripts/tsconfig.ts
index 67a09ab..f6e3c2b 100644
--- a/src/scripts/tsconfig.ts
+++ b/src/scripts/tsconfig.ts
@@ -91,3 +91,27 @@ export function updateTSConfig(
const updatedConfigString = JSON.stringify(updatedConfig, null, 2)
fs.writeFileSync(configFilePath, updatedConfigString, 'utf-8')
}
+
+export function resolveImportPath(
+ baseUrl: string,
+ importPath: string,
+ paths: Record
+): string | undefined {
+ const moduleResolutionHost: ts.ModuleResolutionHost = {
+ fileExists: ts.sys.fileExists,
+ readFile: ts.sys.readFile,
+ realpath: ts.sys.realpath,
+ getCurrentDirectory: () => baseUrl,
+ getDirectories: ts.sys.getDirectories,
+ directoryExists: ts.sys.directoryExists,
+ }
+
+ const resolved = ts.resolveModuleName(
+ importPath,
+ baseUrl,
+ { baseUrl, paths },
+ moduleResolutionHost
+ )
+
+ return resolved.resolvedModule?.resolvedFileName
+}
diff --git a/src/updateImports/index.ts b/src/updateImports/index.ts
index 99d55d5..ac7e64d 100644
--- a/src/updateImports/index.ts
+++ b/src/updateImports/index.ts
@@ -1,10 +1,13 @@
import fs from 'fs'
import path from 'path'
-import * as babel from '@babel/parser'
-import * as utils from './utils'
import * as node from './node'
+import * as utils from './utils'
+import { NodeType } from './types.t'
+import * as babel from '@babel/parser'
+import { Statement } from '@babel/types'
+import { resolveImportPath } from '../scripts/tsconfig'
-const getImports = (parsed: any) => {
+const getImports = (parsed: Statement[]) => {
return [
...node.CallExpressionImport(parsed),
...node.TSImportType(parsed),
@@ -14,12 +17,20 @@ const getImports = (parsed: any) => {
]
}
-const getRequires = (parsed: any) => {
+const getRequires = (parsed: Statement[]) => {
return node.CallExpressionRequire(parsed)
}
-export default (type: 'cjs' | 'mjs', files: any[]) => {
- const ext = '.' + type
+export default (
+ rootDir: string,
+ currentOutDir: string,
+ tsconfigBaseUrl: string | undefined,
+ tsconfigPaths: Record | undefined,
+
+ moduleType: 'cjs' | 'mjs',
+ files: string[]
+) => {
+ const ext = '.' + moduleType
return Object.fromEntries(
files.map((filePath) => {
@@ -31,24 +42,63 @@ export default (type: 'cjs' | 'mjs', files: any[]) => {
sourceFilename: filePath,
}).program.body
- const foundFilePaths =
- filePath.endsWith('.ts') || type === 'mjs'
+ const foundImportPaths =
+ filePath.endsWith('.ts') || moduleType === 'mjs'
? getImports(parsedBody)
: getRequires(parsedBody)
+ function updateRelativeImports(node: NodeType) {
+ const shortPath = node.value.replace(/\.js$/i, '')
+ const fullPath = path.join(dirPath, node.value)
+
+ const isExists = utils.isFileExists(files, fullPath)
+ return isExists ? shortPath + ext : shortPath + '/index' + ext
+ }
+
+ function updateResolvedPath(baseUrl: string, resolvedPath: string) {
+ const relativeToCurrentOutDir = path.join(
+ currentOutDir,
+ path.relative(baseUrl, resolvedPath)
+ )
+
+ const shortPath = path.relative(
+ path.dirname(filePath),
+ relativeToCurrentOutDir
+ )
+
+ const shortestPathWithExt =
+ path.dirname(shortPath) + '/' + path.parse(shortPath).name + ext
+
+ const posixSortPathWithExt = path
+ .normalize(shortestPathWithExt)
+ .replace(/\\/g, '/')
+
+ if (posixSortPathWithExt.startsWith('.')) return posixSortPathWithExt
+ return './' + posixSortPathWithExt
+ }
+
const updatedData = utils.getUpdatedData(
data,
- foundFilePaths,
- (node: any) => {
- const shortPath = node.value.replace(/\.js$/i, '')
- const fullPath = path.join(dirPath, node.value)
+ foundImportPaths,
+ (node: NodeType) => {
+ if (node.value.startsWith('.')) {
+ return updateRelativeImports(node)
+ }
+
+ if (!tsconfigBaseUrl || !tsconfigPaths) return
+ const resolvedPath = resolveImportPath(
+ tsconfigBaseUrl,
+ node.value,
+ tsconfigPaths
+ )
- const isExists = utils.isFileExists(files, fullPath)
- return isExists ? shortPath + ext : shortPath + '/index' + ext
+ return (
+ resolvedPath && updateResolvedPath(tsconfigBaseUrl, resolvedPath)
+ )
}
)
- const newFilePath = utils.getNewFilePath(filePath, type)
+ const newFilePath = utils.getNewFilePath(filePath, moduleType)
return [newFilePath, updatedData] as const
})
)
diff --git a/src/updateImports/node.ts b/src/updateImports/node.ts
index 2b6cd1b..b0ac89a 100644
--- a/src/updateImports/node.ts
+++ b/src/updateImports/node.ts
@@ -1,13 +1,14 @@
+import { Statement } from '@babel/types'
import { findNestedItems, isOkString, parseString } from './utils'
-export const TSImportType = (parsed: any) => {
+export const TSImportType = (parsed: Statement[]) => {
return findNestedItems(parsed, 'type', 'TSImportType')
.filter((node) => isOkString(node.argument))
.map((node) => parseString(node.argument))
}
export const ImportDeclaration_ExportNamedDeclaration_ExportAllDeclaration = (
- parsed: any
+ parsed: Statement[]
) => {
return [
findNestedItems(parsed, 'type', 'ImportDeclaration'),
@@ -20,7 +21,7 @@ export const ImportDeclaration_ExportNamedDeclaration_ExportAllDeclaration = (
.map((node) => parseString(node.source))
}
-export const CallExpressionImport = (parsed: any) => {
+export const CallExpressionImport = (parsed: Statement[]) => {
return findNestedItems(parsed, 'type', 'CallExpression')
.filter(
(node) =>
@@ -32,7 +33,7 @@ export const CallExpressionImport = (parsed: any) => {
.map((node) => parseString(node.arguments[0]))
}
-export const CallExpressionRequire = (parsed: any) => {
+export const CallExpressionRequire = (parsed: Statement[]) => {
return findNestedItems(parsed, 'type', 'CallExpression')
.filter(
(node) =>
diff --git a/src/updateImports/types.t.ts b/src/updateImports/types.t.ts
new file mode 100644
index 0000000..6a8c7f5
--- /dev/null
+++ b/src/updateImports/types.t.ts
@@ -0,0 +1,7 @@
+export type NodeType = {
+ start: number
+ end: number
+ value: string
+ rawValue: string
+ filename: string
+}
diff --git a/src/updateImports/utils.ts b/src/updateImports/utils.ts
index e06f91a..7943e8b 100644
--- a/src/updateImports/utils.ts
+++ b/src/updateImports/utils.ts
@@ -1,4 +1,5 @@
import * as fs from 'fs'
+import { NodeType } from './types.t'
export const getUpdatedData = (fileData: any, found: any[], cb: any) => {
const newEntries = [
@@ -20,10 +21,10 @@ export const getUpdatedData = (fileData: any, found: any[], cb: any) => {
}
export const isOkString = (node: any) => {
- return node && node.type === 'StringLiteral' && node.value.startsWith('.')
+ return node && node.type === 'StringLiteral'
}
-export const parseString = (str: any) => ({
+export const parseString = (str: any): NodeType => ({
start: str.start,
end: str.end,
value: str.value,
diff --git a/src/utils.ts b/src/utils.ts
index 5ac0911..27b0037 100644
--- a/src/utils.ts
+++ b/src/utils.ts
@@ -18,19 +18,20 @@ export function getVersion() {
return packageJSON.read(path.join(__dirname, '../')).version
}
-export function getNodeModulesTempDir(baseDir: string) {
+export function getNodeModulesTempDir(baseDir: string, suffix: string) {
const nodeModulesDir = path.join(baseDir, './node_modules/' + config.name)
+ const outDir = './.temp-dist-' + suffix
if (fs.existsSync(nodeModulesDir)) {
- return path.join(nodeModulesDir, config.tempOutDir)
+ return path.join(nodeModulesDir, outDir)
} else {
const nodeModulesDir = path.join(baseDir, './node_modules')
if (fs.existsSync(nodeModulesDir)) {
- return path.join(nodeModulesDir, config.tempOutDir)
+ return path.join(nodeModulesDir, outDir)
}
}
- return path.join(baseDir, config.tempOutDir)
+ throw new Error('Could not find node_modules directory')
}
export function moveFiles(