电子“需求未定义”

时间:2019-02-05 23:20:28

标签: javascript html node.js electron

我正在制作一个需要授予文件系统(fs)模块访问权限的应用程序,但是即使启用了nodeIntegration,渲染器也会给我这个错误:

Uncaught ReferenceError: require is not defined

我能找到的所有类似问题都有一个解决方案,该解决方案表明它们需要打开nodeIntegration,但是我已经启用了它。

这是我的main.js:

const electron = require('electron');   
const {app, BrowserWindow} = electron;  

let win;

app.on('ready', () => {
    var { width, height } = electron.screen.getPrimaryDisplay().workAreaSize;
    width = 1600;
    height = 900;
    win = new BrowserWindow({'minHeight': 850, 'minWidth': 1600, width, height, webPreferences: {
        contextIsolation: true,
        webSecurity: true,
        nodeIntegration: true
    }});
    win.setMenu(null);
    win.loadFile('index.html');
    win.webContents.openDevTools()
});

我在index.html中链接为<script src="index.js"></script>的index.js目前仅包含require("fs");,我已注释掉所有其他内容。

即使启用了nodeIntegration,我也不知道为什么要求仍然无法正常工作。

1 个答案:

答案 0 :(得分:3)

您已打开public void Configure(IApplicationBuilder app) { var request = new Request("api/menu/create", Method.POST); request.AddParameter("currentApplicationId", 1, ParameterType.QueryString); app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); // UPDATE : Code above prevented from being able to step into below? app.UseMvc(routes => { routes.MapRoute( name: "default", template: "{controller=Home}/{action=Index}/{id?}"); }); app.Use((context, next) => { var cultureQuery = context.Request.Query["culture"]; if (!string.IsNullOrWhiteSpace(cultureQuery)) { var culture = new CultureInfo(cultureQuery); CultureInfo.CurrentCulture = culture; CultureInfo.CurrentUICulture = culture; } // Call the next delegate/middleware in the pipeline return next(); }); app.Run(async (context) => { await context.Response.WriteAsync( $"Hello {CultureInfo.CurrentCulture.DisplayName}"); }); } (如果要加载远程内容,这是一件好事)。在这种情况下,根据您想对contextIsolation模块执行的操作,可以使用预加载脚本来公开其安全版本。 (注意:您不应将整个fs模块暴露给远程页面!)

以下是以这种方式使用预加载脚本的示例:

fs

如果您仅加载本地页面,而这些页面没有加载或执行不安全的动态内容,则您可以重新考虑使用// main process script const mainWindow = new BrowserWindow({ webPreferences: { contextIsolation: true, nodeIntegration: false, preload: './preload.js' } }) mainWindow.loadURL('https://my-website.com') // preload.js const { readFileSync } = require('fs') // the host page will have access to `window.readConfig`, // but not direct access to `readFileSync` window.readConfig = function () { const data = readFileSync('./config.json') return data } (尽管您仍然可以在{主要过程,并使用IPC来回通信。