"target": "ESNext",
"module": "ESNext"
vite.config.ts:
define: {
'process.version': JSON.stringify(process.version)
},
plugins: [
nodePolyfills({
include: ['path', 'fs', 'stream', 'util', 'crypto', 'url'],
globals: {
global: true
}
})
]
generate_token.ts。该文件在应用程序前端部分的React环境中运行。
import * as jwt from 'jsonwebtoken'
import * as fs from 'fs'
import * as path from 'path'
import { fileURLToPath } from 'url'
const __filename = fileURLToPath(import.meta.url)
const __dirname = path.dirname(__filename)
const APP_ID = process.env.GITHUB_APP_ID as string
const PRIVATE_KEY_PATH = path.join(__dirname, '../../../private-key.pem')
export const generateJwt = () => {
const privateKey = fs.readFileSync(PRIVATE_KEY_PATH, 'utf8')
const payload = {
iat: Math.floor(Date.now() / 1000),
exp: Math.floor(Date.now() / 1000) + 60 * 60,
iss: APP_ID
};
return jwt.sign(payload, privateKey, { algorithm: 'RS256' })
}
在浏览器控制台中的结果是
__dirname is undefined
。这是我主要遵循的chatgpt响应:
https://chatgpt.com/share/67a6235a-4874-800d-800d-a18f-7abccd210d57.我如何工作?
浏览器中没有
fs
(文件系统),因此您不能在React App中使用此类内容。