Skip to content

juanm4/esbuild-alias-paths

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

esbuild-alias-paths

🧩 An esbuild plugin that rewrites TypeScript path aliases into relative paths at build time. This allows you to keep your source code clean with alias imports while shipping valid relative imports to production.


✨ Features

  • 🔄 Converts @alias/some/file to relative imports like ../../some/file.js
  • 🛠 Reads path aliases from your tsconfig.json
  • ✅ Works with CommonJS and require() statements
  • 🚀 Seamless integration into production workflows using esbuild
  • 🧪 Zero-dependency and written in TypeScript

📦 Installation

Install via npm:

npm install --save-dev esbuild-alias-paths

📁 Example tsconfig.json

Make sure your tsconfig.json includes path aliases like this:

{
  "compilerOptions": {
    "baseUrl": ".",
    "paths": {
      "@utils/*": ["src/utils/*"],
      "@lib/*": ["src/lib/*"]
    }
  }
}

🛠 Usage with esbuild

You can use this plugin in your esbuild build script. Here is a complete example:

// build.js or build.ts
import esbuild from 'esbuild';
import { configureAliasPaths } from 'esbuild-alias-paths';

esbuild.build({
  entryPoints: ['./src/index.ts'],
  bundle: true,
  platform: 'node',
  target: 'node20',
  outdir: 'dist',
  format: 'cjs',
  plugins: [configureAliasPaths()],
  write: true,
  metafile: true
});

Important: This plugin only activates in production mode, i.e. when process.env.NODE_ENV === 'production'.

Set it via command line:

NODE_ENV=production node build.js

Or set it inline in scripts:

"scripts": {
  "build": "NODE_ENV=production node build.js"
}

🔍 What It Does

Given the following input:

// Before
const util = require('@utils/helpers');

And this alias config:

"paths": {
  "@utils/*": ["src/utils/*"]
}

The plugin rewrites it at build time to:

// After
const util = require('../../utils/helpers');

This avoids runtime issues where Node.js cannot resolve non-relative paths in production bundles.


⚙️ Options

You can optionally pass a custom tsconfig object:

import tsConfig from './tsconfig.custom.json';
configureAliasPaths(tsConfig);

🔒 Limitations

  • Only works in production mode to avoid modifying dev builds
  • Requires write: false so it can manually transform and emit files

📄 License

MIT


👨‍💻 Author

JUANM4@juanma4


🙌 Contributions

Feel free to open issues or PRs on GitHub. Feedback and improvements are welcome!

About

ESBuild plugin to rewrite TypeScript alias paths to relative paths

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published