Rap*_*l10 12 import node.js typescript reactjs electron
如何解决"Cannot use import statement outside a module"Electron-React-Typescript 应用程序中的著名问题?
//const { app, BrowserWindow } = require('electron');
import { app, BrowserWindow } from 'electron';
Run Code Online (Sandbox Code Playgroud)
错误 :
import { app, BrowserWindow } from 'electron';
^^^^^^
SyntaxError: Cannot use import statement outside a module
Run Code Online (Sandbox Code Playgroud)
在 package.json 中我添加了:
"type": "module",
Run Code Online (Sandbox Code Playgroud)
package.json 中的 devDependency :
"@types/node": "^14.14.28",
"@types/react": "^17.0.2",
"electron": "^11.2.3",
"typescript": "^4.1.5",
"webpack": "^5.21.2"
Run Code Online (Sandbox Code Playgroud)
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",
]
}
Run Code Online (Sandbox Code Playgroud)
我还在 babel.config.json 的插件中添加了:
["@babel/plugin-transform-modules-commonjs", {
"allowTopLevelThis": true
}],
Run Code Online (Sandbox Code Playgroud)
并在 package.json 中:
"scripts": {
"babel": "babel ./src/**/* -d dist",
"start": "yarn run babel && electron .",
Run Code Online (Sandbox Code Playgroud)
我必须添加/修改什么才能使用“导入”?
感谢 Electron 的专家,我发现了导致该问题的两个错误:
我修改了package.json中main的路径
"main": "./src/main/main.ts"--->"main": "./dist/main/main.js"
因为电子只能理解编译后的文件
我在 package.js 上删除了
"type": "module"
否则需要更改.js to.cjs 文件
| 归档时间: |
|
| 查看次数: |
7717 次 |
| 最近记录: |