Does esbuild provide a feature like the resolve.alias option in webpack?
const path = require('path');
module.exports = {
//...
resolve: {
alias: {
Utilities: path.resolve(__dirname, 'src/utilities/'),
Templates: path.resolve(__dirname, 'src/templates/'),
},
},
};
Now, instead of using relative paths when importing like so:
import Utility from '../../utilities/utility';
you can use the alias:
import Utility from 'Utilities/utility';
Yes you can, but you have to make sure that the bundle
option is enabled.
If you're using JavaScript, create jsconfig.json file, and if you're using TypeScript, create a tsconfig.json file.
and use the "paths"
compiler option as bellow for example:
{
"compilerOptions": {
"target": "ES2016",
"module": "ESNext",
"moduleResolution": "Bundler", // << you should enable this
"esModuleInterop": true,
"rootDir": "./src",
"outDir": "./dist",
"paths": {
"@/*": ["./src/*"] // << enable this (or your own)
}
},
"include": ["src/**/*"],
"exclude": ["node_modules/**/*"]
}
Then, when running esbuild, make sure to add the --bundle
flag:
// package.json
"scripts": {
"build": "esbuild --bundle ./index.ts # or for js, index.js"
}
$ npm run build
This will resolve imports like this:
import log from '@/tools'
To:
import log from '../../../tools'
Please note that this is only supported if you're using the --bundle
flag, otherwise it will not resolve any alias and it will not show you any warning or an error during build.
If you're only writing code for the back-end, and you're for example not going to bundle your code, because simply you don't care, then, a better solution to you would be using an external plugin, or a third-party npm package for that, such as ts-alias which is pretty cool & easy to use.
If you're doing that for the front-end and you're not using other bundler like webpack or swc, and your main purpose of using esbuild is to bundle your code, then congratulations you're ready to go.