Electron和TypeScript "找不到模块'electron'"

16
关于 electron 对 TypeScript 的支持,请参考 https://electron.atom.io/blog/2017/06/01/typescript。但是,在我的环境中它不起作用:[ts] cannot find module 'electron'。我使用的是 vscode 1.16.1 版本,并且这是我的 package.json 文件内容:
{
  [...]
  "devDependencies": {
    "electron": "^1.6.13",
    "ts-loader": "~2.3.7",
    "typescript": "~2.5.0",
    "webpack": "^3.6.0",
    [...]
  }
}

tsconfig.json

{
    "compilerOptions": {
        "module": "es6",
        "noImplicitAny": true,
        "removeComments": true,
        "preserveConstEnums": true,
        "sourceMap": true
    },
    "include": [
        "src/**/*"
    ]
}

和我的webpack

const path = require('path');

module.exports = [{
  entry: './src/main.ts',
  devtool: 'inline-source-map',
  target: 'electron',
  module: {
    rules: [
      { test: /\.ts$/, use: 'ts-loader', exclude: /node_modules/ }
    ]
  },
  node: {
    __dirname: false,
    __filename: false
  },
  resolve: {
    extensions: [".ts", ".js"]
  },
  output: {
    filename: 'electron_core.js',
    path: path.resolve(__dirname, 'dist')
  }
}  
];

当我在main.ts文件的顶部添加以下内容时

///<reference path="../node_modules/electron/electron.d.ts" />

然后就可以了,我不再有错误了。但是我想避免像这样引用文件,因为在最新版本的typescript中似乎是无用的(请参见如何导入其他TypeScript文件?),而且在electron教程中使用typescript时,他们不需要它...

谢谢


2
tsconfig.json 文件的 compilerOptions 部分中添加 "moduleResolution": "node" 是否有帮助? - Kirill Dmitrenko
完全正确!哇,我为这个缺失的代码行挣扎了很长时间!非常感谢你!也许你可以回答我的问题,而不是评论,这样我就可以将你的答案设置为有效答案 :-) - Adavo
已将其移至回答中 :) - Kirill Dmitrenko
3个回答

25

2
嗨,我也遇到了同样的问题。 import { shell } from "electron"; //提示“找不到模块'electron'”我也按照上面建议的方法更改了tsconfig.json文件。如果有人有正确的解决方法,请帮忙。 - Ravindra Vairagi

3

我这里也遇到了完全相同的问题。它还会影响 VS Code 中的代码自动完成,因为它找不到 "electron" 模块。

这是由于 electron 在 node_module 文件夹中不存在。

如果我执行 npm install electron --save-dev,它就会修复这个问题。


1
如果我们尝试运行Angular应用程序并且未安装Electron,则此方法有效。 - James Shaji

0

如果此问题是由this bug引起而不是上述任何其他问题引起的,则使用node@12是一种临时解决方法。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接