在 Visual Studio Code 中启动 Typescript 应用时抛出错误“找不到模块 'electron'”
在尝试在 Visual Studio Code (VS Code) 中启动一个 TypeScript 应用程序时,我收到错误“Cannot find module 'electron'”。我正在尝试启动的项目是 black-screen,我已经从 GitHub 克隆了它。
此错误在以下语句中抛出:
import {ipcMain, nativeImage} from "electron";(在文件 https://github.com/shockone/black-screen/blob/master/src/main/Main.ts#l3 的第3行)
我可以使用 TypeScript 编译器 (tsc) 转译应用程序,并且没有生成错误,并且可以在我预期的文件夹 (src/bin/) 中看到编译后的 JavaScript。我也可以使用 npm("npm start")成功启动应用程序。
以下是相关的项目配置文件:
src/tsconfig.json
{ "compilerOptions": { "target": "es6", "module": "commonjs", "noImplicitAny": true, "removeComments": true, "preserveConstEnums": true, "moduleResolution": "node", "experimentalDecorators": true, "noEmitOnError": true, "pretty": true, "jsx": "react", "sourceMap": true, "outDir": "bin" } }.vscode/tasks.json 文件 注意。在终端中执行等效命令 "tsc --project src --moduleResolution node" 会生成没有错误或警告的转译后的 js 代码。
{ "version": "0.1.0", "command": "tsc", "isShellCommand": true, "showOutput": "silent", "args": ["--project", "src", "--moduleResolution", "node"], "problemMatcher": "$tsc" }.vscode/launch.json
{ "version": "0.2.0", "configurations": [ { "name": "Launch Black-Screen", "type": "node", "request": "launch", "program": "${workspaceRoot}/src/main/Main.ts", "stopOnEntry": false, "cwd": "${workspaceRoot}/src", "sourceMaps": true, "outDir": "${workspaceRoot}/src/bin" } ] }
顺便说一下,项目结构是:
|.vscode/
|-- launch.json
|-- tasks.json
|decorators/
|...
|node_modules/
|-- bin/
|-- abbrev/
|-- acorn/
|README/
|-- <image files>
|src/
|-- bin/
|-- main/
|---- Main.ts
|---- Menu.ts
|...
|-- tsconfig.json
|...
|stylesheets/
|...
|test/
|...
|typings/
|...
|.babelrc
|.gitignore
|.npmrc
|...
|gulfile.bable.js
|package.json
|...
任何帮助都将不胜感激 :)
答案#1
我修复了调试器无法识别 electron 模块的错误。问题是由于在我的应用程序启动之前,electron 应用程序尚未启动。
我找到一个 StackOverflow 问题和一个相关的博客文章,它们解决了这个问题——使用 Visual Studio Code 调试 Electron-Atom 脚本 /
http://www.mylifeforthecode.com/a-better-way-to-launch-electron-from-visual-studio-code/
将这一行 "runtimeExecutable": "$ {workspaceRoot}/node_modules/electron-prebuilt/dist/electron" 添加到我的 "launch.json" 文件后,electron 在调试器启动之前就已经启动了。
我最终的 "launch.json" 文件是:
{
"version": "0.2.0",
"configurations": [
{
"name": "Launch Black-Screen",
"type": "node",
"request": "launch",
"program": "${workspaceRoot}/src/main/Main.ts",
"stopOnEntry": false,
"cwd": "${workspaceRoot}/src",
"sourceMaps": true,
"outDir": "${workspaceRoot}/src/bin",
"runtimeExecutable": "${workspaceRoot}/node_modules/electron-prebuilt/dist/electron"
}
]
}
调试器会在我设置的断点处停止。我注意到使用调试器时 Electron 的性能要慢得多,但那是另一个问题,我会慢慢解决 :)
答案#2
该项目包含 https://github.com/shockone/black-screen/blob/master/typings/main/ambient/github-electron/github-electron.d.ts,并且模块被声明为: https://github.com/shockone/black-screen/blob/master/typings/main/ambient/github-electron/github-electron.d.ts#L1884
怀疑错误线路:
"args": ["--project", "src", "--moduleResolution", "node"],
更改为:
"args": ["-p", "./src"],
因为这在过去对我有效。
