我已经在main.js中配置了nodeIntegration
、contextIsolation
和enableRemoteModule
。但仍然显示以下消息:
只有当我尝试通过script.js.导入lib.js文件时,才会出现此错误
Uncaught Error: Cannot find module './lib'
Require stack:
- C:UserssergiDocumentsDesenvolvimentophoraselectron-quick-startappindex.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
我使用的是储存库中的电子:储存库
以下是我使用的文件
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);
}
main.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时,我可以做些什么来修复这个错误?
尝试这个lib方法
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 的必读模块系统