node.js 找不到模块“电子”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33922104/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 19:35:33  来源:igfitidea点击:

Cannot find module 'electron'

node.jsnpmatom-editorelectron

提问by Waley Chen

I'm working on a Node.js app that's using the "0.34.3" version of Electron.

我正在开发一个使用“0.34.3”版本 Electron 的 Node.js 应用程序。

The problem that I'm having is that when I try to include the 'electron' module in a renderer process as follows require('electron').remote;and when I npm start--I get the following error:

我遇到的问题是,当我尝试在渲染器进程中包含“电子”模块时,如下所示,require('electron').remote;并且当我npm start出现以下错误时:

{ [Error: Cannot find module 'electron' from '/Users/waley/code/PROJECT/src/connect']
  stream: 
   Labeled {
     _readableState: 
      ReadableState {
        objectMode: true,
        highWaterMark: 16,
        buffer: [],
        length: 0,
        pipes: [Object],
        pipesCount: 1,
        flowing: true,
        ended: false,
        endEmitted: false,
        reading: true,
        sync: false,
        needReadable: true,
        emittedReadable: false,
        readableListening: false,
        defaultEncoding: 'utf8',
        ranOut: false,
        awaitDrain: 0,
        readingMore: false,
        decoder: null,
        encoding: null,
        resumeScheduled: false },
     readable: true,
     domain: null,
     _events: 
      { end: [Object],
        error: [Object],
        data: [Function: ondata],
        _mutate: [Object] },
     _eventsCount: 4,
     _maxListeners: undefined,
     _writableState: 
      WritableState {
        objectMode: true,
        highWaterMark: 16,
        needDrain: false,
        ending: true,
        ended: true,
        finished: true,
        decodeStrings: true,
        defaultEncoding: 'utf8',
        length: 0,
        writing: false,
        corked: 0,
        sync: false,
        bufferProcessing: false,
        onwrite: [Function],
        writecb: null,
        writelen: 0,
        bufferedRequest: null,
        lastBufferedRequest: null,
        pendingcb: 0,
        prefinished: true,
        errorEmitted: false },
     writable: true,
     allowHalfOpen: true,
     _options: { objectMode: true },
     _wrapOptions: { objectMode: true },
     _streams: [ [Object] ],
     length: 1,
     label: 'deps' } }
[11:36:40] js error Cannot find module 'electron' from '/Users/waley/code/PROJECT/src/connect     

Any idea what's up? Thanks!

知道怎么回事吗?谢谢!

回答by martpie

there are a few ways to resolve electron modules import regarding to API Changes Coming in Electron 1.0.

有几种方法可以解决与Electron 1.0 中即将到来的 API 更改相关的电子模块导入。

Please notice this usually occurs with bundler like webpack who override the requirefunction.

请注意,这通常发生在像 webpack 这样覆盖该require函数的捆绑器上。

Make use of Webpack's targetproperty

利用 Webpack 的target属性

If you are using a recent version of Webpack as a bundler, adding

如果您使用最新版本的 Webpack 作为捆绑器,请添加

target: 'electron-renderer'

to your config should let you use:

到您的配置应该让您使用:

import 'electron' from electron;

Declare electronoutside of your build

electron在构建之外声明

<!-- electron declaration -->
<script>
    const electron = require('electron');
</script>

<!-- your app build -->
<script src="dist/bundle.js"></script>

This way, I can access electronfrom anywhere.

这样,我可以electron从任何地方访问。

Use the window.require

使用 window.require

Electron extended the windowobject so that you could use:

Electron 扩展了window对象,以便您可以使用:

const electron = window.require('electron');

Use the old way (still supported)

使用旧方式(仍然支持)

var remote = require('remote');
var app    = remote.app; // to import the app module, for example

回答by Deepak Chawla

Run this command:

运行此命令:

npm install --save-dev electron

for more details click here

欲了解更多详情,请点击此处

回答by STIKO

I got this error when I forgot to add "main": "./main.js",to package.jsonsomewhere before scripts. For complete setup follow this great tutorial

当我忘记在脚本之前添加"main": "./main.js",package.json某处时出现此错误。要完成设置,请遵循这个很棒的教程

Edit:

编辑:

Here's a summery of that link:

这是该链接的摘要:

Install Electron

安装电子

npm install electron --save-dev

Update index.html

更新 index.html

The generated root page in Angular points the base href to / - this will cause problems with Electron later on, so let's update it now. Just add a period in front of the slash in src/index.html.

在 Angular 中生成的根页面将 base href 指向 / - 这将导致 Electron 稍后出现问题,所以现在让我们更新它。只需在 src/index.html 中的斜杠前面添加一个句点。

<base href="./">

Configure Electron

配置电子

Create a new file named main.jsin the root of your project (at the same level as package.json) - this is the Electron NodeJS backend. This is the entry point for Electron and defines how our desktop app will react to various events performed via the desktop operating system.

main.js在项目的根目录中创建一个新文件(与 处于同一级别package.json) - 这是 Electron NodeJS 后端。这是 Electron 的入口点,定义了我们的桌面应用程序将如何对通过桌面操作系统执行的各种事件做出反应。

const { app, BrowserWindow } = require('electron')

let win;

function createWindow () {
  // Create the browser window.
  win = new BrowserWindow({
    width: 600, 
    height: 600,
    backgroundColor: '#ffffff',
    icon: `file://${__dirname}/dist/assets/logo.png`
  })


  win.loadURL(`file://${__dirname}/dist/index.html`)

  //// uncomment below to open the DevTools.
  // win.webContents.openDevTools()

  // Event when the window is closed.
  win.on('closed', function () {
    win = null
  })
}

// Create window on electron intialization
app.on('ready', createWindow)

// Quit when all windows are closed.
app.on('window-all-closed', function () {

  // On macOS specific close process
  if (process.platform !== 'darwin') {
    app.quit()
  }
})

app.on('activate', function () {
  // macOS specific close process
  if (win === null) {
    createWindow()
  }
})

Add main.jsand custom scripts to package.json. Your package.jsonshould look something like this:

添加main.js和自定义脚本到package.json. 你package.json应该看起来像这样:

{
  "name": "angular-electron",
  "version": "0.0.0",
  "license": "MIT",
  "main": "main.js", // <-- update here
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e",
    "electron": "electron .", // <-- run electron 
    "electron-build": "ng build --prod && electron ." // <-- build app, then run electron 
  },
  // ...omitted
}

Run the command to build and launch electron

运行命令来构建和启动电子

npm run electron-build