esbuild-plugin-alias

raw JSON →
0.2.1 verified Mon Apr 27 auth: no javascript

esbuild plugin for creating path aliases, allowing dynamic resolution of import paths based on conditions like environment variables. Version 0.2.1 is the current stable release. The plugin requires absolute file paths for aliases. It is a lightweight alternative to using esbuild's built-in `alias` or custom onResolve plugins, specifically designed for conditional aliasing. It ships TypeScript definitions and is published on npm.

error Error: Could not resolve 'settings.env'
cause Alias value is a relative path instead of absolute.
fix
Use path.resolve() to convert the value to an absolute path.
error TypeError: alias is not a function
cause Named import { alias } when the package exports a default function.
fix
Use default import: import alias from 'esbuild-plugin-alias' or const alias = require('esbuild-plugin-alias').
error ReferenceError: __dirname is not defined in ES module scope
cause Using CommonJS-only __dirname in ESM context.
fix
Use import.meta.url with fileURLToPath or use path.dirname(new URL(import.meta.url).pathname).
breaking Alias values must be absolute file paths; relative paths will fail silently or resolve incorrectly.
fix Use path.resolve() or require.resolve() to convert relative paths to absolute.
gotcha The plugin does not resolve relative paths starting with './' or '../'; they must be converted to absolute.
fix Use path.resolve(__dirname, relativePath) to generate absolute path.
deprecated No breaking changes reported; all versions are stable.
fix N/A
npm install esbuild-plugin-alias
yarn add esbuild-plugin-alias
pnpm add esbuild-plugin-alias

Creates an alias for 'settings.env' resolving to a path that depends on the NODE_ENV environment variable.

import alias from 'esbuild-plugin-alias';
import esbuild from 'esbuild';
import path from 'path';

await esbuild.build({
  entryPoints: ['src/app.js'],
  bundle: true,
  outfile: 'dist/out.js',
  plugins: [
    alias({
      'settings.env': path.resolve(__dirname, 'src', `settings.${process.env.NODE_ENV ?? 'dev'}.js`),
    }),
  ],
});