Electron和TypeScript:'fs'无法解析

use*_*686 2 typescript webpack electron

我正在尝试创建我的第一个Electron应用程序.我决定使用以下工具/技术:

  • 打字稿
  • WebPack(版本3)
  • 应对

当地环境是OS X High Sierra.

问题是我甚至无法构建我的应用程序,并且在使用WebPack进行构建时遇到错误:" Module not found: Error: Can't resolve 'fs' in '<root>/node_modules/electron'"

我有以下配置:package.json:

  "dependencies": {
    "electron": "^1.7.11"
  },
  "devDependencies": {
    "ts-loader": "^3.3.1",
    "tslint": "^5.9.1",
    "typescript": "^2.6.2",
    "webpack": "^3.10.0"
  }
Run Code Online (Sandbox Code Playgroud)

tsconfig.json:

{
  "compileOnSave": false,
  "compilerOptions": {
    "allowJs": true,
    "jsx": "react",
    "moduleResolution": "node",
    "noImplicitAny": true,
    "outDir": "./dist/",
    "sourceMap": true,
    "target": "es2015"
  }
}
Run Code Online (Sandbox Code Playgroud)

webpack.config.js:

const path = require('path');

module.exports = {
    entry: './src/index.ts',
    devtool: 'inline-source-map',
    module: {
        rules: [
            {
                test: /\.tsx?$/,
                use: 'ts-loader',
                exclude: /node_modules/
            }
        ]
    },
    // node: {
    //     'fs': 'empty'
    // },
    resolve: {
        extensions: [ '.tsx', '.ts', '.js' ]
    },
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, 'dist')
    }
};
Run Code Online (Sandbox Code Playgroud)

最后,我./src/index.ts从电子教程中获取的唯一源代码文件()如下所示:

import { app, BrowserWindow } from 'electron';
import * as path from 'path';
import * as url from 'url';

let win: Electron.BrowserWindow;

function createWindow () {
    // ... common stuff
}

app.on('ready', createWindow);
app.on('window-all-closed', () => { if (process.platform !== 'darwin') { app.quit(); }});
app.on('activate', () => { if (win === null) { createWindow(); }});
Run Code Online (Sandbox Code Playgroud)

我认为这个问题与TypeScript的使用方式有关,因为如果我将这些代码从index.ts放到普通的js文件中,它就可以正常工作(将'import'替换为'require').

在此先感谢您的帮助!

更新

如果设置{ target: 'node', }webpack.config.js再有就是对构建步骤没有错误,但如果我尝试打开应用程序,我得到:

App threw an error during load
Error: Electron failed to install correctly, please delete node_modules/electron and try installing again
Run Code Online (Sandbox Code Playgroud)

重新安装节点模块没有帮助.

use*_*686 9

好的,最后我发现解决方案对我有用.应该在中定义'目标'选项webpack.config.js.它不应该{ target: 'node' }像我之前尝试过的那样

如图所示,Webpack具有针对电子应用的特定目标设置,因此正确的方法是设置它:

{
    // for files that should be compiled for electron main process
    target: 'electron-main'
}
Run Code Online (Sandbox Code Playgroud)

要么

{
    // for files that should be compiled for electron renderer process
    target: 'electron-renderer'
}
Run Code Online (Sandbox Code Playgroud)

而已.只需要仔细阅读文档: - (

  • 由于某种原因,这对我不起作用;我的 webpack 配置中有一定程度的间接性,我通过 `create-react-app` 并使用 `rescripts` 来指定 WebPack 目标。但是,我确信目标已正确设置,但我仍然无法解析“fs”等。 (2认同)