Skip to content

fix(nextjs): Add file extensions to relative imports in the ESM build #6442

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 3 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
57 changes: 56 additions & 1 deletion packages/nextjs/tsup.config.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,61 @@
import { readdir, readFile, writeFile } from 'fs/promises';
import { join } from 'path';
import type { Options } from 'tsup';
import { defineConfig } from 'tsup';

import { runAfterLast } from '../../scripts/utils';
// @ts-ignore
import { name, version } from './package.json';

async function addJsExtensionsToEsmFiles() {
const distDir = './dist/esm';

async function findJsFiles(dir: string): Promise<string[]> {
const files: string[] = [];
const entries = await readdir(dir, { withFileTypes: true });

for (const entry of entries) {
const fullPath = join(dir, entry.name);
if (entry.isDirectory()) {
files.push(...(await findJsFiles(fullPath)));
} else if (entry.name.endsWith('.js')) {
files.push(fullPath);
}
}

return files;
}

function addJsExtensions(content: string): string {
return content.replace(/from\s+['"](\.\.?\/[^'"]*?)['"]/g, (match, importPath) => {
if (importPath.match(/\.[a-zA-Z0-9]+$/)) {
return match;
}
return `from '${importPath}.js'`;
});
}

try {
const files = await findJsFiles(distDir);
let processedCount = 0;

for (const file of files) {
const content = await readFile(file, 'utf8');
const updatedContent = addJsExtensions(content);

if (content !== updatedContent) {
await writeFile(file, updatedContent);
processedCount++;
}
}

if (processedCount > 0) {
console.log(`Added .js extensions to ${processedCount} ESM files`);
}
} catch (error) {
console.error('Error adding .js extensions:', error);
}
}

export default defineConfig(overrideOptions => {
const isProd = overrideOptions.env?.NODE_ENV === 'production';
const shouldPublish = !!overrideOptions.env?.publish;
Expand Down Expand Up @@ -36,6 +87,10 @@ export default defineConfig(overrideOptions => {
const esm: Options = {
...common,
format: 'esm',
outExtension: () => ({
js: '.js',
}),
onSuccess: addJsExtensionsToEsmFiles,
};

const cjs: Options = {
Expand Down
Loading