我最近开始了一个新的项目,使用electron forge和webpack模板。我正在创建一个简单的类来进行身份验证,并希望在nodejs中使用事件系统。我正在使用import语法,但收到一个错误消息,说require未定义。我不希望打开nodeIntegration
,我认为webpack会自动使用nodejs事件系统的browserfy版本:
如果您的代码在Node.js中运行,事件模块是内置的。如果您的代码在浏览器中运行,browserify或webpack等捆绑包也会包含事件模块。
安装browserify事件模块也不能解决这个问题。我也试着排除node_modules/events
文件夹,希望webpack能使用它自己的事件模块,但我没有成功。下面是我的代码:
import { EventEmitter } from 'events';
export default class Auth {
constructor(socket) {
}
setToken(token) {
this.token = token;
localStorage.setItem('token', token);
this.emit('token', token);
}
checkToken() {
if(localStorage.getItem("token") !== null) {
this.setToken(localStorage.getItem("token"));
} else {
this.emit('false', false);
}
}
getToken() {
return localStorage.getItem("token");
}
setAuth(auth) {
this.emit('auth', auth);
this.isAuth = auth;
}
}
以下是我的webpack渲染器配置:
const rules = require('./webpack.rules');
const webpack = require('webpack');
const path = require('path');
const CopyWebpackPlugin = require('copy-webpack-plugin');
rules.push({
test: /\.css$/,
use: [{ loader: 'style-loader' }, { loader: 'css-loader' }],
});
const assets = [ 'assets' ];
const copyPlugins = assets.map((asset) => {
return new CopyWebpackPlugin({
patterns: [{ from: path.resolve(__dirname, 'src/renderer/', asset), to: asset }],
});
});
module.exports = {
// Put your normal webpack config below here
module: {
rules,
},
plugins: [
new webpack.ProvidePlugin({
$: 'jquery',
}),
...copyPlugins
],
resolve: {
alias: {
'components': path.resolve(__dirname, './src/renderer/components'),
'pages': path.resolve(__dirname, './src/renderer/pages'),
'core': path.resolve(__dirname, './src/renderer/core'),
},
extensions: ['.js']
},
};
下面是我的webpack规则配置:
module.exports = [
// Add support for native node modules
{
test: /\.node$/,
use: 'node-loader',
},
{
test: /\.(m?js|node)$/,
parser: { amd: false },
use: {
loader: '@marshallofsound/webpack-asset-relocator-loader',
options: {
outputAssetBase: 'native_modules',
},
},
},
];
下面是错误:
external "events":
Uncaught ReferenceError: require is not defined
at Object.events (external "events":1)
at __webpack_require__ (bootstrap:832)
at fn (bootstrap:129)
at Module../src/renderer/core/Auth.js (Auth.js:1)
at __webpack_require__ (bootstrap:832)
at fn (bootstrap:129)
at Module../src/renderer/index.js (index.js:1)
at __webpack_require__ (bootstrap:832)
at fn (bootstrap:129)
at Object.0 (routes.js:40)
2条答案
按热度按时间mec1mxoz1#
在休息了一会儿之后,我意识到解决办法很简单:
我只需要将以下内容添加到我的渲染器配置中:
yhived7q2#
解决方案是使用来自
electron
的ContextBridge
API作为电子伪造Webpack模板preload.js
main.js
package.json
则使用以下代码将调用本机通知消息