如何解决著名问题 "Cannot use import statement outside a module"
在 Electron-React-Typescript 应用程序中?
//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 的专家,我发现了两个导致该问题的错误:
"main": "./src/main/main.ts"
---> "main": "./dist/main/main.js"
因为 electron 只能理解编译后的文件"type": "module"
否则需要更改 .js to
.cjs 文件关于node.js - 不能在模块 Electron React Typescript 之外使用 import 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66208121/