我正在尝试将本地库导入到 vite-electron TypeScript 项目中。请原谅我对 vite-electron 和 JS 捆绑生态系统缺乏了解,一个月前我还是 JS 和 TS 开发的新手。运行
npm run dev
抛出:
App threw an error during load
ReferenceError: _global is not defined
at Object.<anonymous> (C:\Users\jason.kinnard\winsrc\dse-auto-flash-vite\out\main\index.js:105:1)
at Module._compile (node:internal/modules/cjs/loader:1271:14)
at Module._extensions..js (node:internal/modules/cjs/loader:1326:10)
at Module.load (node:internal/modules/cjs/loader:1126:32)
at Module._load (node:internal/modules/cjs/loader:967:12)
at l._load (node:electron/js2c/asar_bundle:2:13642)
at ModuleWrap.<anonymous> (node:internal/modules/esm/translators:169:29)
at ModuleJob.run (node:internal/modules/esm/module_job:194:25)
在我的
src/main/index.ts
中,我打电话给import ../globals
import "../globals"
import { app, shell, BrowserWindow } from 'electron'
import { join } from 'path'
import { electronApp, optimizer, is } from '@electron-toolkit/utils'
import icon from '../../resources/icon.png?asset'
function createWindow(): void {
// Create the browser window.
const mainWindow = new BrowserWindow({
width: 900,
height: 670,
show: false,
autoHideMenuBar: true,
...(process.platform === 'linux' ? { icon } : {}),
webPreferences: {
preload: join(__dirname, '../preload/index.js'),
sandbox: false
}
})
// etc....
在
src/globals.ts
中,运行以下代码:
import "js-globals"
const _global = (global as any)
// stuff gets attached to _global further down in the file.
js-globals
是一个本地 JavaScript 库,我已将其放置在源根目录 ./lib
中,并通过以下 package.json
条目进行安装:
"devDependencies": {
"@electron-toolkit/eslint-config-prettier": "^2.0.0",
"@electron-toolkit/eslint-config-ts": "^1.0.1",
"@electron-toolkit/tsconfig": "^1.0.1",
"@types/node": "^18.19.5",
"@types/react": "^18.2.47",
"@types/react-dom": "^18.2.18",
"@vitejs/plugin-react": "^4.2.1",
"electron": "^28.1.1",
"electron-builder": "^24.9.1",
"electron-vite": "^2.0.0",
"eslint": "^8.56.0",
"eslint-plugin-react": "^7.33.2",
"js-globals": "file:lib/js-globals-3.13.0.tgz",
"prettier": "^3.1.1",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"typescript": "^5.3.3",
"vite": "^5.0.11"
}
我的
tsconfig.node.json
看起来如下:
{
"extends": "@electron-toolkit/tsconfig/tsconfig.node.json",
"include": [
"electron.vite.config.*",
"src/main/*",
"src/preload/*",
"src/globals.ts"
],
"compilerOptions": {
"allowJs": true,
"composite": true,
"resolveJsonModule": true,
"types": ["electron-vite/node"]
}
}
所以我包括
globals.ts
并允许 JS。 out
中编译后的JavaScript在代码中有_global
,但没有_global
的初始定义。这可能是什么原因造成的?
注意,我愿意接受任何更可接受的方式,以全局方式在我的代码中包含本地库,我正在使用另一个非 Vite 项目作为参考,将该库全局地添加到我的代码中。
问题是
js-globals
包含在devDependencies
中,而不是dependencies
中。电子开发和运行的非 Vite 方式electron /path/to/index.js
似乎允许这样做,同时允许应用程序解决其运行时依赖关系。