Skip to content

Commit

Permalink
fix: use try-catch with dynamic imports so that they can be replaced …
Browse files Browse the repository at this point in the history
…with require during bundling (#262)
  • Loading branch information
brc-dd authored Jun 2, 2024
1 parent 4be6dcf commit 1c2e382
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 13 deletions.
2 changes: 1 addition & 1 deletion .github/workflows/test.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ jobs:
- name: Checkout the repository
uses: actions/checkout@v4
- name: Install pnpm
uses: pnpm/action-setup@v2
uses: pnpm/action-setup@v3
with:
version: 9
- name: Install Node.js
Expand Down
25 changes: 14 additions & 11 deletions src/req.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ let tsx

let jiti

let importError
let importError = []

/**
* @param {string} name
Expand All @@ -28,9 +28,11 @@ async function req(name, rootFile = __filename) {
}

if (tsx === undefined) {
tsx = await import('tsx/cjs/api').catch(error => {
importError = error
})
try {
tsx = await import('tsx/cjs/api')
} catch (error) {
importError.push(error)
}
}

if (tsx) {
Expand All @@ -39,20 +41,21 @@ async function req(name, rootFile = __filename) {
}

if (jiti === undefined) {
jiti = await import('jiti').then(
m => m.default,
error => {
importError = importError ?? error
}
)
try {
jiti = (await import('jiti')).default
} catch (error) {
importError.push(error)
}
}

if (jiti) {
return jiti(rootFile, { interopDefault: true })(name)
}

throw new Error(
`'tsx' or 'jiti' is required for the TypeScript configuration files. Make sure it is installed\nError: ${importError.message}`
`'tsx' or 'jiti' is required for the TypeScript configuration files. Make sure it is installed\nError: ${importError
.map(error => error.message)
.join('\n')}`
)
}

Expand Down
2 changes: 1 addition & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"compilerOptions": {
"module": "Preserve",
"module": "node16",
"esModuleInterop": true,
"allowJs": true,
"noEmit": true
Expand Down

0 comments on commit 1c2e382

Please sign in to comment.