我尝试在后端(Express & TS)和前端(Vite React)之间共享常见的zod模型和JS函数,共享库位于gcloud npm repo上。共享库在前端上运行良好,但我经常在后端收到以下错误。
请注意,ResponseErrorModel似乎在后端工作正常,但是PatientModel和LoginFormModel不起作用,无论我尝试什么(所有相关解决方案都是在10个小时的故障排除和研究中找到的)。
- 如果我在Backend package.json配置中添加了type module或jscomon,错误就消失了,但全栈应用程序不再工作:
LoginRequest.ts:4 POST http://localhost:8080/api/login 500 (Internal Server Error)
- 我已经尝试了所有已知的与ES/Common、入口点、index.ts和index.json相关的Backendpackage.json和ts.configs的排列。
- 我已经尝试直接使用'export * from ./forms/LoginModel'导入LogingFormModel,我还尝试删除 * 并替换为{LoginModel}
错误:“意外的令牌'export'”
图书馆信息:
- 包.json*
{
"name": "@something/something-shared",
"version": "1.0.13",
"description": "A nice greeter",
"main": "lib/index.js",
"types": "lib/index.d.ts",
"scripts": {
"clean": "rimraf lib/*",
"build": "tsc",
"format": "prettier --write \"src/**/*.ts\"",
"lint": "tslint -p tsconfig.json",
"prepare": "npm run build",
"prepublishOnly": "npm run lint",
"preversion": "npm run lint",
"postversion": "git push && git push --tags",
"patch": "npm version patch",
"publish": "npm publish",
"artifact-registry-login": "npx google-artifactregistry-auth"
},
"keywords": [],
"author": "someone",
"license": "ISC",
"devDependencies": {
"@types/node": "^18.15.11",
"prettier": "^2.8.7",
"rimraf": "^4.4.1",
"tslint": "^6.1.3",
"tslint-config-prettier": "^1.18.0",
"typescript": "^5.0.2"
},
"files": [
"lib/**/*"
],
"dependencies": {
"zod": "^3.21.4"
}
}
- tsconfig.json*
{
"compilerOptions": {
"target": "ESNext",
"module": "ESNext",
"declaration": true,
"outDir": "./lib",
"strict": true,
"moduleResolution": "Node"
},
"include": ["src"],
"exclude": ["node_modules", "**/__tests__/*"]
}
后端信息
- 导入时库的结构 *
backend package.json
{
"name": "something-backend",
"version": "1.0.0",
"description": "",
"main": "index.ts",
"scripts": {
"dev": "concurrently \"npx tsc --watch\" \"nodemon -q dist/index.js\"",
"build": "npx tsc",
"start": "node dist/index.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@something/something-shared": "^1.0.13",
"dotenv": "^16.0.3",
"express": "^4.18.2",
"kysely": "^0.23.5",
"pg": "^8.10.0",
"zod": "^3.21.4"
},
"devDependencies": {
"@types/express": "^4.17.17",
"@types/node": "^18.15.11",
"@types/pg": "^8.6.6",
"concurrently": "^8.0.1",
"nodemon": "^2.0.22",
"prettier": "^2.8.7",
"typescript": "^5.0.2"
}
}
- backend tsconfig.json *:我尝试了不同的目标和模块类型。
{
"compilerOptions": {
"outDir": "./dist",
"target": "es2016",
"module": "commonjs",
"forceConsistentCasingInFileNames": true,
"strict": true,
"skipLibCheck": true,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true
}
}
1条答案
按热度按时间b1zrtrql1#
如果其他人也遇到了这个问题,根本原因似乎是某些通用工具在库和后端之间没有很好地发挥作用,可能是因为不同的语法和工具交互。后端express应用程序和共享库中的ts配置中的模块/目标设置匹配(和重建/重新部署共享库)是解决它的最有可能的…这是一个仔细的相互作用,我认为之间的旧技术的表达和一些合理的现代前端(这是我对自己所做的最好的理解)。
共享库
这个库的Target和Module被设置为ESNext(Which express environment can 't handle),现在它们匹配了。
无变化,无
"type": "module or commonjs"
后端Express
设置以下内容,确保根索引文件是ts而不是js
作品,相同的目标和模块作为共享库和前端也可以理解共享库没有修改(从而克服了表达的限制,我相信。