typescriptwebpackelectron

Electron and typescript "Cannot find module 'electron'"


Regarding https://www.electronjs.org/blog/typescript, Electron now supports TypeScript, but it's 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 it's ok and 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


Solution

  • 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.