node.js - 不能在模块 Electron React Typescript 之外使用 import 语句

标签 node.js reactjs typescript import electron

如何解决著名问题 "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 :11.2.3
  • typescript :4.1.5
  • Node :v14.5.0
  • 操作系统: Ubuntu 18.04.4 桌面

  • 为了能够使用“导入”,我必须添加/修改什么?

    最佳答案

    感谢 Electron 的专家,我发现了两个导致该问题的错误:

  • 我在 package.json 中修改了 main 的路径"main": "./src/main/main.ts" ---> "main": "./dist/main/main.js"因为 electron 只能理解编译后的文件
  • 我在 package.js 中删除了"type": "module"否则需要更改 .js to .cjs 文件
  • 关于node.js - 不能在模块 Electron React Typescript 之外使用 import 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66208121/

    相关文章:

    reactjs - react-redux的useSelector如何输入?

    css - react / typescript : Idiomatic code for custom components that merge attributes?

    javascript - Visual Studio Code 中的 .ts 文件没有智能感知

    node.js - 使用异步数据库编程对操作进行排序

    node.js - 在 Heroku 上使用 NodeJS 进行 HTML5 音频转换

    javascript - React Redux - 当他们返回该页面时如何在特定位置使用

    javascript - Axios - 未捕获( promise )错误 : Request failed with status code 500

    javascript - React 如何更新样式坐标

    angular - 无法绑定(bind)到 'x',因为它不是 'y' 的已知属性

    javascript - 如何动态设置TinyMCE编辑器内容