【问题标题】:Electron version 12 error: Uncaught Error: Cannot find moduleElectron 版本 12 错误:未捕获错误:找不到模块
【发布时间】:2021-07-07 02:14:50
【问题描述】:

我已经在 main.js 中配置了 nodeIntegrationcontextIsolationenableRemoteModule。但仍会出现以下消息:

仅当我尝试通过 script.js 导入 lib.js 文件时才会发生此错误。

Uncaught Error: Cannot find module './lib'
Require stack:
- C:\Users\sergi\Documents\Desenvolvimento\phoras\electron-quick-start\app\index.html
    at Module._resolveFilename (internal/modules/cjs/loader.js:887)
    at Function.o._resolveFilename (electron/js2c/renderer_init.js:33)
    at Module._load (internal/modules/cjs/loader.js:732)
    at Function.f._load (electron/js2c/asar_bundle.js:5)
    at Function.o._load (electron/js2c/renderer_init.js:33)
    at Module.require (internal/modules/cjs/loader.js:959)
    at require (internal/modules/cjs/helpers.js:88)
    at script.js:1

我正在使用以下版本:

  • 电子:v12.0.2

  • NodeJS:v12.5.0

  • NPM:v6.9.0

  • 我正在使用来自该存储库的电子:repository

以下是我正在使用的文件

app/index.html

<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Index</title>
</head>
<body>
    <script type="module" src="./js/script.js"></script>
</body>
</html>

app/js/script.js

const {lib} = require('./lib'); // this is where the error is happening

lib.message('hello');

app/js/lib.js

function message(msg) {
    console.log(msg);
}

ma​​in.js

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

function createWindow () {

  const mainWindow = new BrowserWindow({
    width: 800,
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, 'preload.js'),
      nodeIntegration: true,
      contextIsolation: false,
      enableRemoteModule: true,
    }    
  })
  mainWindow.loadFile('app/index.html')
}

app.whenReady().then(() => {
  createWindow()
  app.on('activate', function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow()
  })
})

app.on('window-all-closed', function () {
  if (process.platform !== 'darwin') app.quit()
})

尝试导入 lib.js 时如何解决此错误?

【问题讨论】:

  • 你试过require("./lib.js")吗? lib.js 是否与script.js 在同一目录中?
  • @Phil 我也试过了,还是不行
  • 另外,lib.js 似乎没有导出任何东西,这可能是它没有显示为可导入模块的原因
  • 试试这个并以这种方式导出你的函数。常量消息 = () => { };导出默认消息; ------- import message from './lib.js' 如果这对你有用,我会给你一个更干净的方法来做到这一点
  • wallah 恭喜编码愉快,请接受我的回答。

标签: javascript html electron


【解决方案1】:

试试这个库方法

 export function square(x) { return x * x; } 

这样称呼---

import { square} from 'lib';
 console.log(square(11));

----- 或 ------

import * as lib from 'lib';
 console.log(lib.square(11));

必须阅读 JavaScript 的模块系统

【讨论】:

猜你喜欢
  • 2017-08-10
  • 2021-11-24
  • 2015-11-22
  • 2018-12-01
  • 1970-01-01
  • 2022-10-25
  • 2022-08-13
  • 2017-05-18
  • 2019-08-03
相关资源
最近更新 更多