首页 > 解决方案 > NodeJS & 电子和导入

问题描述

我正在尝试import在 Electron 应用程序中使用子句。我有最基本的设置

1/ npm init
2/ npm i -D electron@latest

而已

包.json:

{
  "name": "electron-stable",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "electron ."
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "electron": "^13.2.2"
  }
}

index.js

import {app, BrowserWindow, Menu, ipcRenderer} from 'electron';

我得到一个错误(npm run start):

[Window Title]
Error

[Main Instruction]
A JavaScript error occurred in the main process

[Content]
Uncaught Exception:
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: E:\work\node.js\_tests\electron\electron-stable\index.js
require() of ES modules is not supported.
require() of E:\work\node.js\_tests\electron\electron-stable\index.js from E:\work\node.js\_tests\electron\electron-stable\node_modules\electron\dist\resources\default_app.asar\main.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from E:\work\node.js\_tests\electron\electron-stable\package.json.

    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1096:13)
    at Module.load (internal/modules/cjs/loader.js:935:32)
    at Module._load (internal/modules/cjs/loader.js:776:14)
    at Function.f._load (electron/js2c/asar_bundle.js:5:12913)
    at loadApplicationPackage (E:\work\node.js\_tests\electron\electron-stable\node_modules\electron\dist\resources\default_app.asar\main.js:110:16)
    at Object.<anonymous> (E:\work\node.js\_tests\electron\electron-stable\node_modules\electron\dist\resources\default_app.asar\main.js:222:9)
    at Module._compile (internal/modules/cjs/loader.js:1078:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1108:10)
    at Module.load (internal/modules/cjs/loader.js:935:32)
    at Module._load (internal/modules/cjs/loader.js:776:14)

[OK]
  1. 我试过有/没有"type": "module"
  2. 我尝试使用文件扩展名(js,mjs)
  3. 我不想使用 require (我知道它有效)
  4. 我不想依赖第 3 方包/捆绑器/工具

有没有办法在本地做到这一点,还是电子有问题?谢谢

标签: node.jselectron

解决方案


推荐阅读