簡體   English   中英

不能在模塊外使用 import 語句 Electron React Typescript

[英]Cannot use import statement outside a module Electron React Typescript

如何解決 Electron-React-Typescript 應用程序中著名的問題"Cannot use import statement outside a module"

//const { app, BrowserWindow } = require('electron');
import { app, BrowserWindow } from 'electron';

錯誤:

import { app, BrowserWindow } from 'electron';
^^^^^^
SyntaxError: Cannot use import statement outside a module

在 package.json 我補充說:

"type": "module",

package.json 中的 devDependencies:

"@types/node": "^14.14.28",
"@types/react": "^17.0.2",
"electron": "^11.2.3",
"typescript": "^4.1.5",
"webpack": "^5.21.2"

tsconfig.json:

{
  "compilerOptions": {
    "target": "ES2018",
    "module": "CommonJS",
    "lib": ["dom", "esnext"],
    "outDir": "dist",
    "declaration": true,
    "declarationMap": true,
    "noEmit": true,
    "jsx": "react",
    "strict": true,
    "pretty": true,
    "sourceMap": true,
    "skipLibCheck": true,
    "noImplicitAny": false,
    "noImplicitThis": false,
    /* Additional Checks */
    "noUnusedLocals": true,
    "noUnusedParameters": true,
    "noImplicitReturns": true,
    "noFallthroughCasesInSwitch": true,
    /* Module Resolution Options */
    "moduleResolution": "node",
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "resolveJsonModule": true,
    "allowJs": true
  },
  "include": ["src/**/*"],
  "exclude": [
    "src/index.js",
    "dist",
  ]
}

我還在 babel.config.json 的插件中添加了:

["@babel/plugin-transform-modules-commonjs", {
  "allowTopLevelThis": true
}],

在 package.json 中:

"scripts": {
   "babel": "babel ./src/**/* -d dist",
   "start": "yarn run babel && electron .",
  • electron:11.2.3
  • typescript:4.1.5
  • 節點:v14.5.0
  • 操作系統:Ubuntu 18.04.4 桌面

為了能夠使用“導入”,我必須添加/修改什么?

感謝 Electron 的專家,我發現了兩個導致該問題的錯誤:

  1. 我在 package.json 中修改了主路徑

    "main": "./src/main/main.ts" ---> "main": "./dist/main/main.js"

    因為 electron 只能理解編譯后的文件

  2. 我在 package.js 上刪除了

    "type": "module"

    否則 wuold 需要將.js to .cjs 文件

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM