Reputation: 419
I've already configured nodeIntegration
, contextIsolation
and enableRemoteModule
in main.js. But the following message still appears:
This error only happens when I try to import the lib.js file through the script.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
I am using the following version:
Electron: v12.0.2
NodeJS: v12.5.0
NPM: v6.9.0
I'm using electron from that repository: repository
Below are the files that I am using
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()
})
What can I do to fix this error when trying to import lib.js?
Upvotes: 0
Views: 1127
Reputation: 544
Try this lib method
export function square(x) { return x * x; }
call that way ---
import { square} from 'lib';
console.log(square(11));
----- OR ------
import * as lib from 'lib';
console.log(lib.square(11));
must read Module systems for JavaScript
Upvotes: 1