项目概况

typescript配置说明

2026-01-292 min read前端技术
guide

typescript配置说明

无法找到__dirname

__dirname 是commonjs规范的内置变量。如果使用了esm 是不会自动注入这个变量的。 解决办法。

  • "module": "CommonJS"
text
1{ 2 "compilerOptions": { 3 "composite": true, 4 "tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo", 5 "skipLibCheck": true, 6 "target": "ES2020", 7 "module": "CommonJS", 8 "moduleResolution": "node", 9 "allowSyntheticDefaultImports": true, 10 "strict": true, 11 "noEmit": true, 12 "paths": { 13 "@/*": [ 14 "src/*" 15 ] 16 } 17 }, 18 "include": ["vite.config.ts"] 19}

或者

text
1// 方法一 2import { URL, fileURLToPath } from "node:url"; 3 4// 获取__filename 5function getCurrnetFile () { 6 return fileURLToPath(import.meta.url); 7} 8// 获取__dirname 9function getCurrnetDir () { 10 const url = new URL(".", import.meta.url); 11 return fileURLToPath(url); 12} 13

或者

text
1// 方法二 2import { dirname } from "node:path"; 3import { fileURLToPath } from "node:url"; 4 5// 获取__filename 6function getCurrnetFile () { 7 return fileURLToPath(import.meta.url); 8} 9// 获取__dirname 10function getCurrnetDir () { 11 const __filename = fileURLToPath(import.meta.url); 12 const __dirname = dirname(__filename); 13 return __dirname; 14} 15

解决了这个问题 ts编译不会报错,但是页面加载还是会报错。

text
1import {defineConfig} from 'vite' 2import vue from '@vitejs/plugin-vue' 3import {resolve} from 'path' 4 5// https://vitejs.dev/config/ 6export default defineConfig({ 7 plugins: [vue()], 8 resolve: { 9 alias: { 10 "@": resolve(__dirname, 'src'), // 路径别名 11 }, 12 extensions: ['.js', '.json', '.ts'] // 使用路径别名时想要省略的后缀名,可以自己 增减 13 } 14}) 15

配置参数

text
1{ 2 // 用来配置编译选项 3 "compilerOptions": { 4 "target": "esnext",// 生成js 的版本,下一版本 5 "module": "esnext", // 生成的module的形式,esm,cmd,amd啥的 6 "strict": false, // 是否严格模式 7 "jsx": "preserve", // jsx用于的开发环境,preserve/react/RN 8 "importHelpers": true, // 指定是否引入tslib里的复制工具函数 9 "moduleResolution": "node", // 用于选择模块解析策略 node/classic 10 "experimentalDecorators": true, // 用于指定是否启用实验性的装饰器特性 11 "esModuleInterop": true, // 通过导入内容创建命名空间,实现CommonJS和ES模块之间的互操作性 12 "allowSyntheticDefaultImports": true, // 用于允许从没有默认导出的模块中默认导入 13 "sourceMap": true, // 编译时是否生成.map文件 14 "baseUrl": ".",// 用于设置解析非相对模块名称的基本目录,相对模块不会受到baseUrl的影响 15 //用于指定需要包含的模块,只有在这里列出的模块的声明文件才会被加载 16 "types": [ 17 "webpack-env" 18 ], 19 // 用于设置模块名到基于baseUrl的路径映射 20 "paths": { 21 "@/*": [ 22 "src/*" 23 ] 24 }, 25 // 指定要包含在编译中的库文件 26 "lib": [ 27 "esnext", 28 "dom", 29 "dom.iterable", 30 "scripthost" 31 ] 32 }, 33 // 指定编译的文件,没有include和exclude时候用 34 "file": [], 35 // 指定待编译的文件 36 "include": [ 37 // ** : 任意目录 , * : 任意文件 38 "src/**/*.ts", 39 ], 40 // 指定排除的文件 41 "exclude": [ 42 "node_modules" 43 ] 44} 45 46