Skip to content
Open
Changes from 2 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