I'm discovering Electron and I'm facing a problem: I can't implement my "common.js" file in my "test.js" script.
Here is the architecture of my project:
rootProject
-features(folder)
-common.js
-test.js
-index.html
common.js
const hello = "hello";
module.exports = { hello };
test.js
const {hello} = require("./common.js");
console.log(hello);
index.html
<body>
<h1>Hello World!</h1>
<div class="flex-container">
<span id="timeAfterRefreshGasFees"></span>
<span id="rapid"></span>
<span id="fast"></span>
<span id="standard"></span>
<span id="slow"></span>
</div>
<!-- You can also require other files to run in this process -->
<script src="./renderer.js"></script>
<!-- <script src="./features/common.js"></script> -->
<script src="./features/test.js"></script>
</body>
In this case, I got: Error: Cannot find module './common.js'
And if I uncomment <script in index.html , I got this error: Identifier 'hello' has already been declared
I want to have a common.js file where I can put stuff inside (like const etc...)
How can I fix it?
I already tried all these solution: Getting Unexpected Token Export
Thank you!
EDIT after first solution:
I added these lines to get nodeIntegration
webPreferences: {
nodeIntegration: true,
contextIsolation: false,
preload: path.join(__dirname, 'preload.js')
}
And removed <script in common.js
<script src="./features/common.js"></script>
But now, I have this error when I'm trying to require in test.js : Cannot find module './common.js'
The problem is with the require() not existing in the client-side javacript
An answer more developed: https://stackoverflow.com/a/19059825/11224089
Like @brunocordioli072 said require
is only a Node.js function, and by default Node.js functions are disabled in Electron.
Because this is Javascript you can use <script>
tags like you're doing to include files.
And if I uncomment <script in index.html, I got this error: Identifier 'hello' has already been declared
This is because hello
is already defined in common.js
and because your including common.js
with a <script>
tag you can already use it inside test.js
without using require
.
Side note:
If you really need to use require
or other Node.js functions you can simply turn on nodeIntegration
and turn off contextIsolation
in your BrowserWindow settings like this:
new BrowserWindow({
webPreferences: {
nodeIntegration: true,
contextIsolation: false
},
});
However this will create security problems in your app.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.