Skip to content

Commit

Permalink
fix: correctly add file extensions for dynamic imports (#149)
Browse files Browse the repository at this point in the history
* fix: add file extension to dynamic imports

required for TanStack/router#2190

* fix: add file extension for multiline imports/exports

required for TanStack/router#2190
  • Loading branch information
schiller-manuel authored Aug 27, 2024
1 parent 0f1a390 commit 3e83866
Showing 1 changed file with 25 additions and 13 deletions.
38 changes: 25 additions & 13 deletions packages/config/src/vite/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,26 @@ import { externalizeDeps } from 'vite-plugin-externalize-deps'
import tsconfigPaths from 'vite-tsconfig-paths'
import dts from 'vite-plugin-dts'

/**
*
* @param {{content: string, extension: string}} params
* @returns
*/
function ensureImportFileExtension({ content, extension }) {
// replace e.g. `import { foo } from './foo'` with `import { foo } from './foo.js'`
content = content.replace(
/(im|ex)port\s[\w{}/*\s,]+from\s['"]\.\/[^.'"]+(?=['"];?)/gm,
`$&.${extension}`,
)

// replace e.g. `import('./foo')` with `import('./foo.js')`
content = content.replace(
/import\(['"]\.\/[^.'"]+(?=['"];?)/gm,
`$&.${extension}`,
)
return content
}

/**
* @param {import('./index.js').Options} options
* @returns {import('vite').UserConfig}
Expand All @@ -30,14 +50,10 @@ export const tanstackViteConfig = (options) => {
module: 99, // ESNext
declarationMap: false,
},
beforeWriteFile: (filePath, content) => {
content = content.replace(
/^(im|ex)port\s[\w{}*\s,]+from\s['"]\.\/[^.'"]+(?=['"];?$)/gm,
'$&.js',
)

return { filePath, content }
},
beforeWriteFile: (filePath, content) => ({
filePath,
content: ensureImportFileExtension({ content, extension: 'js' }),
}),
}),
dts({
outDir: `${outDir}/cjs`,
Expand All @@ -50,11 +66,7 @@ export const tanstackViteConfig = (options) => {
declarationMap: false,
},
beforeWriteFile: (filePath, content) => {
content = content.replace(
/^(im|ex)port\s[\w{}*\s,]+from\s['"]\.\/[^.'"]+(?=['"];?$)/gm,
'$&.cjs',
)

content = ensureImportFileExtension({ content, extension: 'cjs' })
filePath = filePath.replace('.d.ts', '.d.cts')

return { filePath, content }
Expand Down

0 comments on commit 3e83866

Please sign in to comment.