问题
I've been refactoring this code into public and I'm using this to solve some past mistakes. Like writing my save and load functions.
I need to load in my code some JSON files. Doesn't matter where if I can access it here https://github.com/cicerohellmann/3DBRPG/blob/board/board/boardView.js
I've run into most of the possible solutions when trying to bring a file inside of electron or work arounds for not being able to use require or include in my js files after opening my project with electron instead of node.
window.fs = require("fs") wont do,
preloading with electron I couldn't make it work (this is actually my best shot yet),
<script>
window.nodeRequire = require;
delete window.require;
delete window.exports;
delete window.module;
</script>
<script type="text/javascript" src="jquery.js"></script>
doesn't work either
the branch I'm working is this one https://github.com/cicerohellmann/3DBRPG/tree/board even then I should be working our something in a branch called "save/load"
回答1:
I found a solid solution that doesn't raise any security flags, for now:
This is my main.js create window method:
function createWindow () {
mainWindow = new BrowserWindow({
width: 800,
height: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js')
}
});
mainWindow.loadFile('index.html')
mainWindow.on('closed', function () {
mainWindow = null
});
}
Observe that I added "__dirname", which is a method that grabes the current path, and added my preload.js script
this is my preload.js script:
window.fs = require('fs');
window.path = __dirname;
I found very usefull to import this "__dirname" method with it since the current path for my local files will probably change in the future and other people machines.
now you can load and save files using "window.fs"
Here is my dataManagement class: https://github.com/cicerohellmann/3DBRPG/blob/dataManagement_save_load/dataManagement.js
来源:https://stackoverflow.com/questions/61618828/load-local-json-into-electron-cant-use-require-include