如何解决 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 .",
我必须添加/修改什么才能使用“导入”?
答案 0 :(得分:0)
感谢 Electron 的专家,我发现了导致该问题的两个错误:
我在 package.json 中修改了 main 的路径
"main": "./src/main/main.ts"
---> "main": "./dist/main/main.js"
因为电子只能理解编译后的文件
我在 package.js 上删除了
"type": "module"
否则需要更改 .js to
.cjs 文件