学习的时候遇到一个问题,不知道哪位能帮忙解答一下,我想扩展第三方模块的接口类型,单独建了一个myenv.d.ts文件来申明,但是在使用的时候始终无效。
myenv.d.ts文件
import 'dotenv'
declare module 'dotenv' {
export interface DotenvParseOutput {
VITE_BASE_URL: string
VITE_HOST: string
VITE_PORT: number
VITE_PROXY_DOMAIN: string
}
}
在.env.development中
VITE_HOST="127.0.0.1"
VITE_PORT=5000
VITE_BASE_URL='/dang'
VITE_PROXY_DOMAIN='http://192.168.2.6:6000/'
在vite.config.ts中使用
import { defineConfig, CommonServerOptions } from 'vite'
import vue from '@vitejs/plugin-vue'
import dotenv,{DotenvParseOutput} from 'dotenv'
import fs from 'fs'
export default defineConfig(
(mode) => {
const envFileName: string = '.env'
const curEnvFileName = `${envFileName}.${mode.mode}`
let server: CommonServerOptions = {}
const envData = fs.readFileSync(curEnvFileName)
const envMap:DotenvParseOutput = dotenv.parse(envData)
if (mode.mode === 'development') {
server = {
host: , //正常在这里使用envMap,应该可以直接点出VITE_HOST,但是系统没有提示
port:, //在这里写envMap.VITE_PORT,会提示类型不对,要用string,显然扩展的接口并没有合并进来
proxy: {
[]: {
target:
}
}
}
console.log('我是开发环境', server);
} else if (mode.mode === 'production') {
console.log('我是生产环境');
}
return {
plugins: [vue()],
server
}
}
)
在tsconfig.json配置是这样的
"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue", "src/declare_/myenv.d.ts"],
版本如下:
"dependencies": {
"dotenv": "^16.3.1",
"vue": "^3.2.47"
},
"devDependencies": {
"@types/node": "^20.4.0",
"@vitejs/plugin-vue": "^4.1.0",
"typescript": "^5.0.2",
"vite": "^4.3.9",
"vue-tsc": "^1.4.2"
}
}
查了好久也没找到问题所在,还麻烦各位有没有知道原因的。
根据您提供的代码和说明,我认为问题可能出在您的模块扩展声明文件的文件名上。您将其命名为myenv.d.ts
,但是在tsconfig.json
中,您将其包含在了src/declare_/
目录下。因此,TypeScript 可能无法找到该声明文件。
我建议您将myenv.d.ts
文件放在src
目录下,并将其包含在include
选项中,如下所示:
"include": ["src/**/*.ts", "src/**/*.d.ts", "src/**/*.tsx", "src/**/*.vue", "src/myenv.d.ts"],
此外,您可以在tsconfig.json
文件中添加以下compilerOptions
选项,以检查您的声明文件是否正确:
"compilerOptions": {
"noUnusedLocals": true,
"noUnusedParameters": true,
"noImplicitReturns": true,
"noFallthroughCasesInSwitch": true,
"strictNullChecks": true,
"strictFunctionTypes": true,
"strictPropertyInitialization": true,
"noImplicitAny": true,
"esModuleInterop": true,
"skipLibCheck": true
}
这些选项可以帮助您在编译时检测到未使用的变量和参数,未使用的代码路径以及可能为空的值等问题。
最后,您可以尝试将您的模块扩展声明放在一个全局声明文件中,例如global.d.ts
,并将其包含在tsconfig.json
的include
选项中。这样可以确保您的声明文件在整个项目中都是可用的。