未捕获ReferenceError:未定义require;当nodeIntegration设置为false

时间:2019-04-07 23:14:48

标签: javascript reactjs electron

我正在尝试使用Electron,React和TypeScript创建一个应用程序(我的想法现在似乎对我来说是一场噩梦)。我正在使用电子预编译来转译我的代码。 我的意图是使nodeIntegration为false。但是,如果执行此操作,则会显示错误:

未捕获的ReferenceError:require未定义     在index.html:inline_0.js:2

我尝试添加一些通行预设,但是这些并没有帮助我。我也在那里添加了CommonJS预设。但是它仍然失败。

将nodeIntegration保持为false的原因是,我不希望在renderer.js中访问它,因为它带来了安全隐患。

//。compilerc

"env": {
    "development": {
      "application/javascript": {
        "presets": [
          [
            "env",
            {
              "targets": {
                "electron": "4.1.3"
              }
            }
          ],
          "react",
          "es2016-node5"
        ],
        "plugins": [
          "react-hot-loader/babel",
          "dynamic-import-node",
          ["transform-es2015-modules-commonjs", {
      "allowTopLevelThis": true
    }],
          "transform-async-to-generator",
          "transform-es2015-modules-commonjs"
        ],
        "sourceMaps": "inline"
      },
      "text/html": {
        "pretty": true
      }
    },

// package.json

{
  "name": "master-dashboard",
  "version": "1.0.0",
  "description": "Master Dashboard",
  "main": "app/index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "electron .",
    "postinstall": "electron-rebuild"
  },
  "keywords": [
  ],
  "author": "Kaustav Sarkar",
  "license": "MIT",
  "dependencies": {
    "electron": "^4.1.3",
    "electron-compile": "^6.4.4",
    "react": "^16.8.6",
    "react-dom": "^16.8.6"
  },
  "devDependencies": {
    "babel-plugin-dynamic-import-node": "^2.2.0",
    "babel-plugin-transform-es2015-modules-commonjs": "^6.26.2",
    "electron-prebuilt-compile": "^4.0.0",
    "electron-rebuild": "^1.8.4",
    "react-hot-loader": "^4.8.2"
  }

}

// index.html

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>My   Page</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" type="text/css" media="screen"         href="index.css">
</head>

<body>
    <div id="master"></div>
</body>
<script type="application/javascript">
    require('./renderers/renderer')
</script>

</html>

// index.js要点

const createWindow = () => {
    win = new BrowserWindow({
        center: true,
        resizable: true,
        webPreferences: {
            nodeIntegrationInWorker: false,
            nodeIntegration: false,
            show: false
        }
    });
    win.maximize();
    win.webContents.openDevTools();

win.loadURL(url.format({
    pathname: path.join(__dirname, 'index.html'),
    slashes: true,
    protocol: 'file'
}), { "extraHeaders": "Cache-Control: no-cache\n" });

0 个答案:

没有答案