[英]Typescript, React, Electron: Cannot use import statement outside a module
[英]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 的專家,我發現了兩個導致該問題的錯誤:
我在 package.json 中修改了主路徑
"main": "./src/main/main.ts"
---> "main": "./dist/main/main.js"
因為 electron 只能理解編譯后的文件
我在 package.js 上刪除了
"type": "module"
否則 wuold 需要將.js to
.cjs 文件
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.