使用 webpack 打包 Electron 应用程序时出现错误Cannot resolve module 'electron'
Cannot resolve module 'electron'
我正在尝试使用React创建一个Electron应用程序。我使用Webpack来编译React JSX语法,但是当我尝试使用命令进行编译时,出现了以下错误:webpack
webpack
./app.jsx 中出现错误,未找到模块:错误:无法解析 /Users/masterT/Downloads/gist 中的模块“electron” @ ./app.jsx 6:18-37
./app.jsx 中出现错误,未找到模块:错误:无法解析 /Users/masterT/Downloads/gist 中的模块“electron”
@ ./app.jsx 6:18-37
这是应用程序代码。
您看到的错误消息表明 Webpack 无法解析该electron模块。这是因为electron这是一个原生模块,Webpack 不会像其他依赖项那样对其进行打包。
electron
要解决此问题,您需要对 Webpack 配置和项目设置进行一些调整:
externals``electron
以下是实现此目标的步骤:
/project-root /src /main main.js /renderer app.jsx index.html package.json webpack.main.config.js webpack.renderer.config.js
webpack.main.config.js
```js const path = require(‘path’);
module.exports = { entry: ‘./src/main/main.js’, target: ‘electron-main’, output: { path: path.resolve(__dirname, ‘dist’), filename: ‘main.js’ }, node: { __dirname: false, __filename: false } }; ```
webpack.renderer.config.js
module.exports = { entry: ‘./src/renderer/app.jsx’, target: ‘electron-renderer’, module: { rules: [ { test: /.jsx?$/, exclude: /node_modules/, use: ‘babel-loader’ } ] }, resolve: { extensions: [‘.js’, ‘.jsx’] }, output: { path: path.resolve(__dirname, ‘dist’), filename: ‘renderer.js’ }, externals: { electron: ‘require(“electron”)’ } }; ```
sh npm install --save-dev webpack webpack-cli babel-loader @babel/core @babel/preset-env @babel/preset-react npm install react react-dom electron
.babelrc
json { "presets": ["@babel/preset-env", "@babel/preset-react"] }
package.json
json { "name": "your-electron-app", "version": "1.0.0", "main": "dist/main.js", "scripts": { "build-main": "webpack --config webpack.main.config.js", "build-renderer": "webpack --config webpack.renderer.config.js", "build": "npm run build-main && npm run build-renderer", "start": "electron ." }, "devDependencies": { "webpack": "^5.x.x", "webpack-cli": "^4.x.x", "babel-loader": "^8.x.x", "@babel/core": "^7.x.x", "@babel/preset-env": "^7.x.x", "@babel/preset-react": "^7.x.x" }, "dependencies": { "react": "^17.x.x", "react-dom": "^17.x.x", "electron": "^13.x.x" } }
运行应用程序:
使用 构建应用程序npm run build。
npm run build
npm start
通过遵循这些步骤,你应该能够使用 Webpack 和 React 编译你的 Electron 应用程序,而不会遇到模块解析错误electron。