【问题标题】:Require doesn't appear in my code, but webpack keeps throwing the error "require is not defined."Require 没有出现在我的代码中,但是 webpack 不断抛出错误“require is not defined”。
【发布时间】:2020-04-19 13:42:25
【问题描述】:

我正在编写一个带有反应的电子应用程序。我使用以下命令运行开发版本:

webpack-dev-server --hot --host 0.0.0.0 --port 4000 --config=./webpack.dev.config.js

这里是 webpack.dev.config.js 文件

const webpack = require('webpack');
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const { spawn } = require('child_process');
const helpers = require('./config/helpers');


// Config directories
const SRC_DIR = path.resolve(__dirname, 'src');
const OUTPUT_DIR = path.resolve(__dirname, 'dist');

// Any directories you will be adding code/files into, need to be added to this array so webpack will pick them up
const defaultInclude = [SRC_DIR];

module.exports = {
  entry: SRC_DIR + '/index.js',
  output: {
    path: OUTPUT_DIR,
    publicPath: '/',
    filename: 'bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [{ loader: 'style-loader' }, { loader: 'css-loader' }],
        include: defaultInclude
      },
      {
        test: /\.jsx?$/,
        use: [{ loader: 'babel-loader' }],
        include: defaultInclude
      },
      {
        test: /\.(jpe?g|png|gif)$/,
        use: [{ loader: 'file-loader?name=img/[name]__[hash:base64:5].[ext]' }],
        include: defaultInclude
      },
      {
        test: /\.(eot|svg|ttf|woff|woff2)$/,
        use: [{ loader: 'file-loader?name=font/[name]__[hash:base64:5].[ext]' }],
        include: defaultInclude
      }
    ]
  },
  target: 'electron-renderer',
  plugins: [
    new HtmlWebpackPlugin({
      template: helpers.root('public/index.html'),
      inject: 'body'
    }),
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': JSON.stringify('development')
    })
  ],
  devtool: 'cheap-source-map',
  devServer: {
    contentBase: OUTPUT_DIR,
    stats: {
      colors: true,
      chunks: false,
      children: false
    },
    setup() {
      spawn(
        'electron',
        ['.'],
        { shell: true, env: process.env, stdio: 'inherit' }
      )
      .on('close', code => {
        console.error("electron exited with code ", code);
        process.exit(0)
      })
      .on('error', spawnError => console.error(spawnError));
    }
  }
};

electron 浏览器打开后,在 Dev-Tools 控制台中会出现以下错误。

Uncaught ReferenceError: require is not defined
    at Object.url (index.js:23)
    at __webpack_require__ (bootstrap:709)
    at fn (bootstrap:94)
    at Object../node_modules/webpack-dev-server/client/utils/createSocketUrl.js (createSocketUrl.js:4)
    at __webpack_require__ (bootstrap:709)
    at fn (bootstrap:94)
    at Object.<anonymous> (client:20)
    at Object../node_modules/webpack-dev-server/client/index.js?http://0.0.0.0:4000 (client:176)
    at __webpack_require__ (bootstrap:709)
    at fn (bootstrap:94)

它声称发生这种情况的地方是 index.js:23。

这里是 index.js 的构建版本:

import React from "react";
import { render } from "react-dom";
import { Provider } from "react-redux";
import App from "./components/App";
import { createStore, applyMiddleware } from "redux";
import thunk from "redux-thunk";
import { ipcRenderer as ipc } from "electron";
import { onUpdate } from "./actions/workerActions";
import { RECEIVED_STATE } from "./actions/types";
import "./assets/css/index.css";
import rootReducer from "./reducers/rootReducer";
import defaultState from "../config/defaultstate"; //Setup redux store

const middleware = [thunk];
const store = createStore(rootReducer, defaultState, applyMiddleware(...middleware));
ipc.on(RECEIVED_STATE, arg => {
  console.log("Recieved State: ", arg);
  onUpdate(arg)(store.dispatch);
}); // Now we can render our application into it

render(React.createElement(Provider, {
  store: store
}, React.createElement(App, null)), document.getElementById("app"));

正如您所见,require 没有出现在这里,除了 ipcRender 之外的所有导入都设计为在客户端运行,因此不应使用 required。我尝试注释掉 ipcRender 导入,但它导致了完全相同的错误。

最令人费解的是,即使将整个 index.js 文件注释掉,我也会遇到完全相同的错误。 控制台仍然声称块注释包含对未定义的 require 的引用。

【问题讨论】:

  • 它可能来自你的 webpack 配置
  • @alex067 怎么样,配置在应用程序打开之前运行,以便构建 dist 文件夹并打开开发服务器。它使用 require 的事实应该无关紧要。你是说配置中的一个选项正在这样做吗?
  • 可能是这个:stackoverflow.com/questions/51978775/… ...一旦你修复它,请确保你清除浏览器缓存。

标签: javascript webpack electron webpack-dev-server


【解决方案1】:

如果您直接使用 webpack,请确保您的 webpack 配置中有以下针对您的渲染器代码的配置。

// webpack.config.js
...
module.exports = {
 ...
 target: 'web',
 ...
}

如果您使用的是 Vue,那么您将需要以下内容:

// vue.config.js
...
module.exports = {
 ...
 configureWebpack: {
   target: 'web'
 },
 ...
}

或者,就我而言,我使用的是vue-cli-plugin-electron-builder,因此需要以下内容:

// vue.config.js
...
module.exports = {
  ...
  pluginOptions: {
    electronBuilder: {
      nodeIntegration: false,
      chainWebpackRendererProcess: config => {
        config.target('web');
      }
    }
  },
  ...
}

【讨论】:

    【解决方案2】:

    原来错误是导入electron的ipcRenderer导致的,需要node集成,使用require。在 index.js 中注释掉 import 并没有修复错误的原因是因为它是在其他文件中导入的。

    【讨论】:

      猜你喜欢
      • 2021-06-11
      • 1970-01-01
      • 2021-11-08
      • 2021-03-29
      • 2022-12-05
      • 2020-05-03
      • 1970-01-01
      • 2022-12-01
      • 2020-08-30
      相关资源
      最近更新 更多