找不到模塊“電子” (Cannot find module 'electron')


問題描述

找不到模塊“電子” (Cannot find module 'electron')

我正在開發一個使用“0.34.3”版本 Electron 的 Node.js 應用程序。

我遇到的問題是,當我嘗試包含“電子”時渲染器進程中的模塊如下 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     

知道發生了什麼嗎?謝謝!


參考解法

方法 1:

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

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

Make use of Webpack's target property

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

target: 'electron‑renderer'

to your config should let you use:

import 'electron' from electron;

Declare electron outside of your build

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

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

This way, I can access electron from anywhere.

Use the window.require

Electron extended the window object so that you could use:

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

方法 2:

Run this command:

npm install ‑‑save‑dev electron

for more details click here

方法 3:

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

Edit:

Here's a summery of that link:

Install Electron

npm install electron ‑‑save‑dev

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

<base href="./">

Configure Electron

Create a new file named main.js in 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.

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.js and custom scripts to package.json. Your package.json should look something like this:

{
  "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

(by Waley ChenmartpieDeepak ChawlaSTIKO)

參考文件

  1. Cannot find module 'electron' (CC BY‑SA 2.5/3.0/4.0)

#npm #electron #atom-editor #node.js






相關問題

TFS 構建中的 npm install 拋出“未找到:git” (npm install in TFS build throws "not found: git")

找不到模塊“電子” (Cannot find module 'electron')

使用 npm 進行生成器角度安裝時出現問題 (Trouble during generator-angular installation with npm)

使用 node.js 從谷歌云存儲中刪除多個對象 (Delete multiple objects fron google cloud storage using node.js)

VS Task Runner Explorer - Node Sass 找不到綁定 (VS Task Runner Explorer - Node Sass could not find a binding)

有什麼東西可以跟踪我安裝的 npm 包並在不同的開發環境中恢復它們嗎?(如“恢復 NuGet 包”) (Is there anything that can keep track of my installed npm packages and restore them on a different dev environment ? (like "Restore NuGet packages"))

角度材質工具欄不繼承自角度材質 (Angular material toolbar not inheriting from angular materials)

npm install throws 和錯誤告訴 node 不是一個可識別的命令 (npm install throws and error telling node is not a recognized command)

從代理後面登錄的無服務器框架? (Serverless Framework Login From Behind a Proxy?)

構建工具結構 - NPM、Grunt 和 Wordpress (Build tools structure - NPM, Grunt with Wordpress)

如何解決 Linux 中的“npm ERR!code ELIFECYCLE”錯誤? (How to solve "npm ERR! code ELIFECYCLE" error in Linux?)

如何在 Angular 中導入“數字”:“^1.2.6”? (How to import "numeric": "^1.2.6" in Angular?)







留言討論