vite
vite copied to clipboard
resolve.alias doesn't work on vite builds
Describe the bug
When I run vite dev, resolve.alias has works.
But, when I run vite build, it won't works.
this is my code:
import { PluginOption, defineConfig } from 'vite';
import * as path from 'path';
function print() {
let init = false;
const plugin: PluginOption = {
name: 'print',
async transform(src, id) {
if (this.resolve && !init) {
console.log('debug', await this.resolve('package-a'));
init = true;
}
},
};
return plugin;
}
export default defineConfig({
resolve: {
alias: {
'package-a': path.resolve(__dirname, './packages/package-a/src'),
},
},
plugins: [print()],
});
Reproduction
https://github.com/moecasts/vite-resolve-alias-build-demo
Steps to reproduce
pnpm i && pnpm --filter 'package-*' build && pnpm build
System Info
System:
OS: macOS 13.3
CPU: (10) arm64 Apple M1 Pro
Memory: 367.98 MB / 32.00 GB
Shell: 5.9 - /bin/zsh
Binaries:
Node: 16.19.0 - ~/.nvm/versions/node/v16.19.0/bin/node
Yarn: 1.22.19 - /opt/homebrew/bin/yarn
npm: 8.19.3 - ~/.nvm/versions/node/v16.19.0/bin/npm
pnpm: 7.27.0 - /opt/homebrew/bin/pnpm
Browsers:
Chrome: 114.0.5735.248
Safari: 16.4
npmPackages:
vite: ^4.4.5 => 4.4.7
Used Package Manager
npm
Logs
Click to expand!
> tsc && vite build "--debug"
vite:config bundled config file loaded in 15.10ms +0ms
vite:config using resolved config: {
vite:config resolve: {
vite:config mainFields: [ 'module', 'jsnext:main', 'jsnext' ],
vite:config browserField: true,
vite:config conditions: [],
vite:config extensions: [
vite:config '.mjs', '.js',
vite:config '.mts', '.ts',
vite:config '.jsx', '.tsx',
vite:config '.json'
vite:config ],
vite:config dedupe: [],
vite:config preserveSymlinks: false,
vite:config alias: [ [Object], [Object], [Object] ]
vite:config },
vite:config plugins: [
vite:config 'vite:build-metadata',
vite:config 'vite:watch-package-data',
vite:config 'vite:pre-alias',
vite:config 'alias',
vite:config 'vite:modulepreload-polyfill',
vite:config 'vite:resolve',
vite:config 'vite:html-inline-proxy',
vite:config 'vite:css',
vite:config 'vite:esbuild',
vite:config 'vite:json',
vite:config 'vite:wasm-helper',
vite:config 'vite:worker',
vite:config 'vite:asset',
vite:config 'print',
vite:config 'vite:wasm-fallback',
vite:config 'vite:define',
vite:config 'vite:css-post',
vite:config 'vite:build-html',
vite:config 'vite:worker-import-meta-url',
vite:config 'vite:asset-import-meta-url',
vite:config 'vite:force-systemjs-wrap-complete',
vite:config 'commonjs',
vite:config 'vite:data-uri',
vite:config 'vite:dynamic-import-vars',
vite:config 'vite:import-glob',
vite:config 'vite:build-import-analysis',
vite:config 'vite:esbuild-transpile',
vite:config 'vite:terser',
vite:config 'vite:reporter',
vite:config 'vite:load-fallback'
vite:config ],
vite:config optimizeDeps: {
vite:config disabled: 'build',
vite:config force: undefined,
vite:config esbuildOptions: { preserveSymlinks: false }
vite:config },
vite:config build: {
vite:config target: [ 'es2020', 'edge88', 'firefox78', 'chrome87', 'safari14' ],
vite:config cssTarget: [ 'es2020', 'edge88', 'firefox78', 'chrome87', 'safari14' ],
vite:config outDir: 'dist',
vite:config assetsDir: 'assets',
vite:config assetsInlineLimit: 4096,
vite:config cssCodeSplit: true,
vite:config sourcemap: false,
vite:config rollupOptions: {},
vite:config minify: 'esbuild',
vite:config terserOptions: {},
vite:config write: true,
vite:config emptyOutDir: null,
vite:config copyPublicDir: true,
vite:config manifest: false,
vite:config lib: false,
vite:config ssr: false,
vite:config ssrManifest: false,
vite:config ssrEmitAssets: false,
vite:config reportCompressedSize: true,
vite:config chunkSizeWarningLimit: 500,
vite:config watch: null,
vite:config commonjsOptions: { include: [Array], extensions: [Array] },
vite:config dynamicImportVarsOptions: { warnOnError: true, exclude: [Array] },
vite:config modulePreload: { polyfill: true },
vite:config cssMinify: true
vite:config },
vite:config configFile: '/Users/caster/Developments/lab/vite-resolve-alias-build-demo/vite.config.ts',
vite:config configFileDependencies: [
vite:config '/Users/caster/Developments/lab/vite-resolve-alias-build-demo/vite.config.ts'
vite:config ],
vite:config inlineConfig: {
vite:config root: undefined,
vite:config base: undefined,
vite:config mode: undefined,
vite:config configFile: undefined,
vite:config logLevel: undefined,
vite:config clearScreen: undefined,
vite:config optimizeDeps: { force: undefined },
vite:config build: {}
vite:config },
vite:config root: '/Users/caster/Developments/lab/vite-resolve-alias-build-demo',
vite:config base: '/',
vite:config rawBase: '/',
vite:config publicDir: '/Users/caster/Developments/lab/vite-resolve-alias-build-demo/public',
vite:config cacheDir: '/Users/caster/Developments/lab/vite-resolve-alias-build-demo/node_modules/.vite',
vite:config command: 'build',
vite:config mode: 'production',
vite:config ssr: {
vite:config format: 'esm',
vite:config target: 'node',
vite:config optimizeDeps: { disabled: true, esbuildOptions: [Object] }
vite:config },
vite:config isWorker: false,
vite:config mainConfig: null,
vite:config isProduction: true,
vite:config css: undefined,
vite:config esbuild: { jsxDev: false },
vite:config server: {
vite:config preTransformRequests: true,
vite:config sourcemapIgnoreList: [Function: isInNodeModules],
vite:config middlewareMode: false,
vite:config fs: { strict: true, allow: [Array], deny: [Array] }
vite:config },
vite:config preview: {
vite:config port: undefined,
vite:config strictPort: undefined,
vite:config host: undefined,
vite:config https: undefined,
vite:config open: undefined,
vite:config proxy: undefined,
vite:config cors: undefined,
vite:config headers: undefined
vite:config },
vite:config envDir: '/Users/caster/Developments/lab/vite-resolve-alias-build-demo',
vite:config env: { BASE_URL: '/', MODE: 'production', DEV: false, PROD: true },
vite:config assetsInclude: [Function: assetsInclude],
vite:config logger: {
vite:config hasWarned: false,
vite:config info: [Function: info],
vite:config warn: [Function: warn],
vite:config warnOnce: [Function: warnOnce],
vite:config error: [Function: error],
vite:config clearScreen: [Function: clearScreen],
vite:config hasErrorLogged: [Function: hasErrorLogged]
vite:config },
vite:config packageCache: Map(1) {
vite:config 'fnpd_/Users/caster/Developments/lab/vite-resolve-alias-build-demo' => {
vite:config dir: '/Users/caster/Developments/lab/vite-resolve-alias-build-demo',
vite:config data: [Object],
vite:config hasSideEffects: [Function: hasSideEffects],
vite:config webResolvedImports: {},
vite:config nodeResolvedImports: {},
vite:config setResolvedCache: [Function: setResolvedCache],
vite:config getResolvedCache: [Function: getResolvedCache]
vite:config },
vite:config set: [Function (anonymous)]
vite:config },
vite:config createResolver: [Function: createResolver],
vite:config worker: {
vite:config format: 'iife',
vite:config plugins: [
vite:config 'vite:build-metadata',
vite:config 'vite:watch-package-data',
vite:config 'vite:pre-alias',
vite:config 'alias',
vite:config 'vite:modulepreload-polyfill',
vite:config 'vite:resolve',
vite:config 'vite:html-inline-proxy',
vite:config 'vite:css',
vite:config 'vite:esbuild',
vite:config 'vite:json',
vite:config 'vite:wasm-helper',
vite:config 'vite:worker',
vite:config 'vite:asset',
vite:config 'vite:wasm-fallback',
vite:config 'vite:define',
vite:config 'vite:css-post',
vite:config 'vite:build-html',
vite:config 'vite:worker-import-meta-url',
vite:config 'vite:asset-import-meta-url',
vite:config 'vite:force-systemjs-wrap-complete',
vite:config 'commonjs',
vite:config 'vite:data-uri',
vite:config 'vite:worker-post',
vite:config 'vite:dynamic-import-vars',
vite:config 'vite:import-glob',
vite:config 'vite:build-import-analysis',
vite:config 'vite:esbuild-transpile',
vite:config 'vite:terser',
vite:config 'vite:load-fallback'
vite:config ],
vite:config rollupOptions: {},
vite:config getSortedPlugins: [Function: getSortedPlugins],
vite:config getSortedPluginHooks: [Function: getSortedPluginHooks]
vite:config },
vite:config appType: 'spa',
vite:config experimental: { importGlobRestoreExtension: false, hmrPartialAccept: false },
vite:config getSortedPlugins: [Function: getSortedPlugins],
vite:config getSortedPluginHooks: [Function: getSortedPluginHooks]
vite:config } +4ms
vite v4.4.7 building for production...
debug {
assertions: {},
external: false,
id: '/Users/caster/Developments/lab/vite-resolve-alias-build-demo/packages/package-a/dist/esm/index.js',
meta: {},
moduleSideEffects: true,
resolvedBy: 'vite:resolve',
syntheticNamedExports: false
}
vite:esbuild 14.01ms tsconfck init /Users/caster/Developments/lab/vite-resolve-alias-build-demo +0ms
✓ 7 modules transformed.
dist/index.html 0.45 kB │ gzip: 0.29 kB
dist/assets/typescript-f6ead1af.svg 1.44 kB │ gzip: 0.84 kB
dist/assets/index-3443e464.css 1.24 kB │ gzip: 0.64 kB
dist/assets/index-aa676a50.js 1.45 kB │ gzip: 0.74 kB
✓ built in 70ms
Validations
- [X] Follow our Code of Conduct
- [X] Read the Contributing Guidelines.
- [X] Read the docs.
- [X] Check that there isn't already an issue that reports the same bug to avoid creating a duplicate.
- [X] Make sure this is a Vite issue and not a framework-specific issue. For example, if it's a Vue SFC related bug, it should likely be reported to vuejs/core instead.
- [X] Check that this is a concrete bug. For Q&A open a GitHub Discussion or join our Discord Chat Server.
- [X] The provided reproduction is a minimal reproducible example of the bug.
Vite now has no defineConfig?
I have exactly the same problem. @moecasts, have you found any solutions?
I have exactly the same problem. @moecasts, have you found any solutions?
I had modified the resolve function that replace the alias before the function execute.
async transform(value, path) {
if (!resolve) {
resolve = (source, importer, options) => {
const mergedOptions: typeof options = Object.assign(
{
skipSelf: true,
},
options,
);
const currentAlias = find(alias, { find: source });
if (currentAlias?.replacement) {
const realSource = source.replace(source, currentAlias.replacement);
return this.resolve(realSource, importer, mergedOptions);
}
return this.resolve(source, importer, mergedOptions);
};
}
I am also running into this issue; I actually used configResolved instead but the outcome is the same:
configResolved(resolvedConfig) {
if (resolvedConfig.resolve && Array.isArray(resolvedConfig.resolve?.alias)) {
// These needs to be at the top of the array to take precedence
resolvedConfig.resolve.alias.unshift(
{
find: 'react-native/Libraries/Image/AssetRegistry',
replacement: 'react-native-web/dist/modules/AssetRegistry',
},
{
find: 'react-native-web/Libraries/Image/AssetRegistry',
replacement: 'react-native-web/dist/modules/AssetRegistry',
},
);
console.log(JSON.stringify(resolvedConfig));
}
},
I get errors on build about those paths not existing but I do not on serve.
I am using this configuration to find and replace TypeScript aliases, and it is working in both development and build environments. I hope it proves helpful to you.
import react from '@vitejs/plugin-react';
import { resolve } from 'path';
import { defineConfig } from 'vite';
export default defineConfig({
plugins: [react()],
resolve: {
alias: [
{
find: '@common/components',
replacement: resolve(__dirname, './src/common/components'),
},
{
find: '@common/icons',
replacement: resolve(__dirname, './src/common/icons'),
},
{
find: '@common/layout',
replacement: resolve(__dirname, './src/common/layout'),
},
{
find: '@common/apis',
replacement: resolve(__dirname, './src/common/apis'),
}]
})
Same issue
Same issue too
Hi @hossamt93, When I use similar code:
import react from "@vitejs/plugin-react";
import path from "path";
import { defineConfig } from "vite";
// import { fileURLToPath, URL } from 'node:url'
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
"@": path.resolve(__dirname, "./src/"),
},
},
});
I get this error: Cannot find module 'path' or its corresponding type declarations.
I just created a new React project with TypeScript using vite.
Do I need to install "path"? Should it be in my package.json?
Hi @hossamt93, When I use similar code:
import react from "@vitejs/plugin-react"; import path from "path"; import { defineConfig } from "vite"; // import { fileURLToPath, URL } from 'node:url' // https://vitejs.dev/config/ export default defineConfig({ plugins: [react()], resolve: { alias: { "@": path.resolve(__dirname, "./src/"), }, }, });I get this error:
Cannot find module 'path' or its corresponding type declarations.I just created a new React project with TypeScript using vite. Do I need to install "
path"? Should it be in mypackage.json?
Just run
npm i -D @types/node
Hi @hossamt93, When I use similar code:
import react from "@vitejs/plugin-react"; import path from "path"; import { defineConfig } from "vite"; // import { fileURLToPath, URL } from 'node:url' // https://vitejs.dev/config/ export default defineConfig({ plugins: [react()], resolve: { alias: { "@": path.resolve(__dirname, "./src/"), }, }, });I get this error:
Cannot find module 'path' or its corresponding type declarations.I just created a new React project with TypeScript using vite. Do I need to install "path"? Should it be in mypackage.json?Just run
npm i -D @types/node
@migsdeving
I am having the same problem even after performing npm i -D @types/node.
@itayperry
Did you find any solution?