An ESBuild plugin that fixes import paths by applying the following plugins:
fixAliasPlugin: Resolves path aliases defined intsconfig.json.fixFolderImportsPlugin: Replaces imports pointing to directories with explicit paths to theindexfile.fixExtensionsPlugin: Appends the correct file extensions to relative import paths.
This plugin ensures correct file extensions, resolves path aliases, and fixes directory imports in your build output when using tsup with bundle: false.
Install the package via npm:
npm install esbuild-fix-imports-pluginOr using pnpm:
pnpm add esbuild-fix-imports-pluginOr using Yarn:
yarn add esbuild-fix-imports-pluginesbuild.mjs:
import { build } from "esbuild";
import fg from "fast-glob";
import { fixImportsPlugin, writeFilePlugin } from "esbuild-fix-imports-plugin";
/** @type {import('esbuild').BuildOptions} */
export const common = {
target: "esnext",
platform: "node",
bundle: false, // No bundle
write: false, // Cannot write files to disk, it should be done in memory for the plugins to access the output files
tsconfig: "./tsconfig.json",
plugins: [
fixImportsPlugin(),
writeFilePlugin(), // Write files to disk once the processing is done
],
};
/** collect entry points like tsup's entry + excludes */
const getEntryPoints = async () => await fg(["src/**/*"], { onlyFiles: true });
export const buildAll = async () => {
const entryPoints = await getEntryPoints();
// CJS
const CJSPromise = build({
...common,
entryPoints,
format: "cjs",
outdir: "dist
outExtension: { ".js": ".cjs" },
});
// ESM
const ESMPromise = build({
...common,
entryPoints,
format: "esm",
outdir: "dist/esm",
outExtension: { ".js": ".mjs" },
});
// Execute both builds in parallel for faster execution
await Promise.all([CJSPromise, ESMPromise]);
};
buildAll().catch((err) => {
console.error(err);
process.exit(1);
});package.json:
{
"scripts": {
"build": "node esbuild.mjs"
}
}IMPORTANT: Consider using ESBuild directly as TSUP is d deprecated.
In your tsup.config.ts or ESBuild configuration file, import the plugin and add it to your esbuildPlugins array:
// tsup.config.ts
import { defineConfig } from "tsup";
import { fixImportsPlugin } from "esbuild-fix-imports-plugin";
export default defineConfig({
// ... your other configurations
esbuildPlugins: [fixImportsPlugin()],
});This will apply all three plugins (fixAliasPlugin, fixFolderImportsPlugin, and fixExtensionsPlugin) during the build process.
If you prefer to use the plugins individually, you can import them separately:
import {
fixAliasPlugin,
fixFolderImportsPlugin,
fixExtensionsPlugin,
} from "esbuild-fix-imports-plugin";
export default defineConfig({
// ... your other configurations
esbuildPlugins: [
fixAliasPlugin(),
fixFolderImportsPlugin(),
fixExtensionsPlugin(),
],
});Description: Resolves path aliases defined in your tsconfig.json file and replaces them with relative paths in the output files.
Use Case: When using path aliases in TypeScript, the compiled JavaScript files may contain unresolved import paths. This plugin fixes that by converting aliases to relative paths.
Requirements:
- Ensure your
tsconfig.jsonincludes thepathsconfiguration. - Provide the path to
tsconfig.jsonin yourtsupor ESBuild configuration.
Example tsconfig.json:
{
compilerOptions: {
baseUrl: ".",
paths: {
"@utils/*": ["src/utils/*"],
"@components/*": ["src/components/*"],
},
// ... other options
},
}Description: Replaces import paths pointing to directories with explicit paths to the index file.
Use Case: Some module resolvers do not automatically resolve imports to index files within directories. This plugin ensures that imports like import { myFunction } from './utils'; are transformed to import { myFunction } from './utils/index';.
Description: Appends the correct file extensions (.js, .mjs, .cjs) to relative import paths in the output files.
Use Case: In environments that require explicit file extensions in import statements, this plugin ensures that all relative imports have the correct extensions, preventing runtime errors.
Here's a full example of how to configure tsup with this plugin:
// tsup.config.ts
import { defineConfig } from "tsup";
import { fixImportsPlugin } from "esbuild-fix-imports-plugin";
export default defineConfig([
{
entry: ["src/**/*"],
target: "esnext",
dts: true,
external: ["fs", "path"],
clean: true,
sourcemap: true,
bundle: false, // Important: set to false
tsconfig: "./tsconfig.json",
format: ["cjs"],
outDir: "dist/cjs",
outExtension: () => ({ js: ".cjs" }),
esbuildPlugins: [fixImportsPlugin()],
},
{
entry: ["src/**/*"],
target: "esnext",
dts: true,
external: ["fs", "path"],
clean: true,
sourcemap: true,
bundle: false, // Important: set to false
tsconfig: "./tsconfig.json",
format: ["esm"],
outDir: "dist/esm",
outExtension: () => ({ js: ".mjs" }),
esbuildPlugins: [fixImportsPlugin()],
},
]);Explanation:
bundle: false: Settingbundletofalsetellstsupnot to bundle the modules, which can lead to issues with import paths. This plugin helps resolve those issues.esbuildPlugins: [fixImportsPlugin()]: Applies the combined plugin to fix import paths during the build process.
Description: Writes the output files to disk once the processing is done.
Use Case: This plugin is useful when you want to write the output files to disk after the processing is done.
Contributions are welcome! If you find a bug or have a feature request, please open an issue on GitHub.
-
Fork the Repository: Click the "Fork" button at the top-right corner of the repository page.
-
Clone Your Fork:
git clone https://github.com/aymericzip/esbuild-fix-imports-plugin.git
-
Create a New Branch:
git checkout -b feature/my-new-feature
-
Install Dependencies:
npm install
-
Make Your Changes: Implement your feature or fix.
-
Build the Project:
npm run build
-
Test Your Changes:
npm run test -
Commit Your Changes:
git commit -am 'Add my new feature' -
Push to Your Fork:
git push origin feature/my-new-feature
-
Open a Pull Request: Go to your fork on GitHub and open a pull request to the main repository.
This project is licensed under the ISC License.
Aymeric PINEAU
- GitHub: aymericzip
Note: Remember to adjust the plugin configurations according to your project's specific needs and ensure that all paths and options are correctly set.
Special thanks to the contributors and the open-source community for their continuous support.
When using tsup with bundle: false, you might encounter issues with import paths in the output files, such as missing file extensions, unresolved path aliases, or imports pointing to directories without explicit index files. This plugin automates the process of fixing these issues during the build.
Not necessarily. If you only need to fix specific issues, you can import and apply the individual plugins:
import {
fixAliasPlugin,
fixExtensionsPlugin,
} from "esbuild-fix-imports-plugin";
export default defineConfig({
// ... your other configurations
esbuildPlugins: [fixAliasPlugin(), fixExtensionsPlugin()],
});Environments that require explicit file extensions in imports or do not automatically resolve directory imports to index files will benefit from this plugin. This includes some Node.js configurations and bundlers.
Feel free to open an issue if you have more questions or need assistance.