Adavo
Adavo

Reputation: 925

Electron and typescript "Cannot find module 'electron'"

Regarding https://electron.atom.io/blog/2017/06/01/typescript electron support typescript but is not working on my setup:

[ts] cannot find module 'electron'

I use vscode 1.16.1

Here is my 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/**/*"
    ]
}

and my 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')
  }
}  
];

When I add at the top of my main.ts

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

then is ok I don't have the error anymore. However I would like to avoid referencing files like this as it seems it's useless with the latest version of typescript (see How do I import other TypeScript files?) and moreover in the electron tutorial for typescript they don't need it ...)

Thanks

Upvotes: 16

Views: 12793

Answers (3)

pseudosudo
pseudosudo

Reputation: 6590

Using node@12 is a temporary fix in case this issue is caused by this bug rather than any of the other ones mentioned above.

Upvotes: 0

Muskan Khedia
Muskan Khedia

Reputation: 78

Having the exact same issue here. It also affects code completion in the VS Code since it cannot find the "electron" module.

This happens because electron does not exist in the node_module folder.

If I do npm install electron --save-dev, it fixes the issue.

Upvotes: 3

Kirill Dmitrenko
Kirill Dmitrenko

Reputation: 3619

The problem seems to lie in the way tsc (and tsserver) resoves modules by default.

To use use node.js-like algorithm you need to add "moduleResolution": "node" to "compilerOptions" section of tsconfig.json.

Upvotes: 25

Related Questions