尝试在 VSCode 中转到 import 时,出现错误: 无法打开编辑器,因为找不到文件。
我使用Vite。我在设置中指定了 alias,也在 tsconfig 中指定了它,但这没有帮助。
构建/开发过程正常工作,但我无法在使用别名的文件之间切换。
vite.config.ts
import {
defineConfig,
loadEnv
} from 'vite';
import react from '@vitejs/plugin-react';
import path from 'path';
const {
NODE_ENV
} = process.env;
const nameDevelopment: string = 'development';
const isDev = NODE_ENV === nameDevelopment;
// https://vitejs.dev/config/
export default defineConfig({
base: '',
resolve: {
alias: {
'@styles': path.resolve(__dirname, 'src/assets/styles'),
},
},
css: {
modules: {
localsConvention: 'camelCaseOnly',
// generateScopedName: '[hash:base64:5]',
generateScopedName: isDev ? '[local]__[hash:base64:5]' : '[hash:base64:5]',
// generateScopedName: "prefix-[name]-[hash]",
},
},
plugins: [react()],
server: {
open: true,
host: true,
},
build: {
rollupOptions: {
output: {
chunkFileNames: 'assets/js/[name]-[hash].js',
entryFileNames: 'assets/js/[name]-[hash].js',
assetFileNames: function({
name
}) {
if (/\.(gif|jpe?g|png|svg)$/.test(name ? ? '')) {
return 'assets/img/[name]-[hash][extname]';
}
if (/\.css$/.test(name ? ? '')) {
return 'assets/css/[name]-[hash][extname]';
}
if (/.(png|woff|woff2|eot|ttf)/.test(name ? ? '')) {
return 'assets/fonts/[name]-[hash][extname]';
}
// default value
// ref: https://rollupjs.org/guide/en/#outputassetfilenames
return 'assets/[name]-[hash][extname]';
},
},
},
},
// Функция которая поможет решить проблему путей
experimental: {
renderBuiltUrl: function(filename: string, {
hostId,
hostType,
type
}: {
hostId: string,
hostType: 'js' | 'css' | 'html',
type: 'public' | 'asset'
}) {
// console.log(arguments);
if (type === 'asset') {
if (hostType === 'css') {
const stringRemove = 'assets';
const stringLength = stringRemove.length;
const stringPresence = filename.indexOf(stringRemove);
if (-1 !== stringPresence) {
console.log('..' + filename.substring(stringLength));
return '..' + filename.substring(stringLength);
}
}
}
}
},
});
tsconfig.json
{
"compilerOptions": {
"target": "ES2020",
"useDefineForClassFields": true,
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"module": "ESNext",
"skipLibCheck": true,
/* Bundler mode */
"moduleResolution": "bundler",
"allowImportingTsExtensions": true,
"resolveJsonModule": true,
"isolatedModules": true,
"noEmit": true,
"jsx": "react-jsx",
/* Linting */
"strict": true,
"noUnusedLocals": true,
"noUnusedParameters": true,
"noFallthroughCasesInSwitch": true,
// Custom setting
// "baseUrl": "src",
"baseUrl": ".",
"paths": {
"@styles": ["src/*"],
},
},
"include": ["src"],
"references": [{ "path": "./tsconfig.node.json" }]
}