将本地JSON加载到电子文件中,不能使用require / include [英] Load local JSON into electron, can't use require/include

查看:157
本文介绍了将本地JSON加载到电子文件中,不能使用require / include的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在将此代码重构为公开代码,并正在使用它来解决一些过去的错误。就像编写我的保存和加载函数一样。

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.


我需要在代码中加载一些JSON文件。我
在哪里可以访问这里
https://github.com/cicerohellmann/3DBRPG/blob/board/board/boardView.js

在用电子代替节点打开项目后,试图将文件带入电子或解决无法使用require或包含在我的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)不会做,

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>

也不起作用

我正在工作的分支就是这个 https://github.com/cicerohellmann/3DBRPG/tree/ 即使是这样,我也应该在名为保存/加载的分支中工作。

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"

推荐答案

我发现了一个暂时不产生任何安全标记的可靠解决方案:

I found a solid solution that doesn't raise any security flags, for now:

这是我的main.js创建窗口方法:

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
  });
}

观察到我添加了 __dirname,这是一种获取当前值的方法路径,并添加了我的preload.js脚本

Observe that I added "__dirname", which is a method that grabes the current path, and added my preload.js script

这是我的preload.js脚本:

this is my preload.js script:

window.fs = require('fs');
window.path = __dirname;

自从我的本地文件的当前路径以来,我发现用它导入此 __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.

现在您可以使用 window.fs加载和保存文件了。

now you can load and save files using "window.fs"

这是我的dataManagement类: https://github.com/ cicerohellmann / 3DBRPG / blob / dataManagement_save_load / dataManagement.js

Here is my dataManagement class: https://github.com/cicerohellmann/3DBRPG/blob/dataManagement_save_load/dataManagement.js

这篇关于将本地JSON加载到电子文件中,不能使用require / include的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆