Typescript外部使用import语句

Typescript外部使用import语句

本文介绍了无法在模块Electron React Typescript外部使用import语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何解决Electron-React-Typescript应用程序中的著名问题不能在模块外部使用import语句" ?

How to solve the famous issue "Cannot use import statement outside a module" in an Electron-React-Typescript app?

//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中我添加了:

in package.json I added :

"type": "module",

package.json中的

devDependencies:

devDependencies in package.json :

"@types/node": "^14.14.28",
"@types/react": "^17.0.2",
"electron": "^11.2.3",
"typescript": "^4.1.5",
"webpack": "^5.21.2"

tsconfig.json:

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的插件:

I also added in babel.config.json 's plugins :

["@babel/plugin-transform-modules-commonjs", {
  "allowTopLevelThis": true
}],

并在package.json中:

and in package.json :

"scripts": {
   "babel": "babel ./src/**/* -d dist",
   "start": "yarn run babel && electron .",

  • 电子:11.2.3
  • 打字稿:4.1.5
  • 节点:v14.5.0
  • O.S.:Ubuntu 18.04.4台式机
  • 为了能够使用导入"功能,我必须添加/修改什么??

    What do I have to add / modify in order to be able to use "import" ?

    推荐答案

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

    Thanks to and Electron's expert I discovered two errors which caused that issue:

    1. 我在package.json中修改了主路径

    1. I modified the main's path in package.json

    "main":"../src/main/main.ts" --->"main":"./dist/main/main.js"

    因为电子只能理解编译的文件

    because electron can understand only the compiled file

    我在package.js中删除了

    I removed in package.js on

    类型":模块"

    否则wuold需要将 .js更改为 .cjs文件

    which otherwise wuold require to change .js to .cjs files

    这篇关于无法在模块Electron React Typescript外部使用import语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-18 12:01