首页 > 解决方案 > SyntaxError: 不能在模块外使用 import 语句(Electron & typeORM)

问题描述

我目前正在创建一个 Electron 应用程序(使用 TypeScript);与用于 sqlite3 的 typeORM 一起使用(因为应用程序将涉及大量关系数据)。
我使用了一些我在网上找到的入门代码:

import { app, BrowserWindow } from "electron";
import * as path from "path";

function createWindow() {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, "preload.js"),
    },
    width: 800,
  });

  mainWindow.loadFile(path.join(__dirname, "../index.html"));
}

app.on("ready", () => {
  createWindow();

  app.on("activate", function () {
    if (BrowserWindow.getAllWindows().length === 0) createWindow();
  });
});

app.on("window-all-closed", () => {
  if (process.platform !== "darwin") {
    app.quit();
  }
});

这编译得很好并按原样打开了窗口;带有 HelloWorld 消息;阅读 typeORM 并运行迁移我发现了一些代码并将我的 main.ts 脚本更新为以下内容:

import { app, BrowserWindow } from "electron";
import * as path from "path";

import "reflect-metadata";
import { createConnection } from 'typeorm';

function createWindow() {
  // Create the browser window.
  const mainWindow = new BrowserWindow({
    height: 600,
    webPreferences: {
      preload: path.join(__dirname, "preload.js"),
      worldSafeExecuteJavaScript: true,
      contextIsolation: true
    },
    width: 800,
  });

  mainWindow.loadFile(path.join(__dirname, "../public/index.html"));
}

createConnection().then(async connection => {
  app.on("ready", async () => {

    await connection.runMigrations();

    createWindow();

    app.on("activate", function () {
      if (BrowserWindow.getAllWindows().length === 0) createWindow();
    });

  });
  app.on("window-all-closed", () => {
    if (process.platform !== "darwin") {
      app.quit();
    }
  });
}).catch(error => console.log(error));

突然我得到了上述错误......我做了一些谷歌搜索并找到了一些建议的修复;包括package.json和我的 tsconfig.json"type": "module"的各种组合。targetmodule

为了完整起见,这是我当前的 tsconfig

{
   "compilerOptions": {
      "lib": [
         "DOM",
         "es5",
         "es6"
      ],
      "target": "esnext",
      "module": "commonjs",
      "moduleResolution": "node",
      "emitDecoratorMetadata": true,
      "experimentalDecorators": true,
      "sourceMap": true,
      "outDir": "dist",
      "baseUrl": ".",
      "paths": {
         "*": [
            "node_modules/*"
         ]
      }
   },
   "include": [
      "src/**/*"
   ]
}

和我的 package.json

{
   "name": "rockcollector",
   "version": "0.0.0",
   "description": "An electron app to keep track of and manage your collection of rocks and minerals",
   "author": "Pieter-Jan Cassiman",
   "license": "GPL-3.0-or-later",
   "main": "index.js",
   "scripts": {
      "typeorm": "node --require ts-node/register ./node_modules/typeorm/cli.js",
      "build": "tsc --module commonjs --target esnext",
      "watch": "tsc --module commonjs --target esnext -w",
      "lint": "eslint -c .eslintrc --ext .ts ./src",
      "start": "npm run build && electron ./dist/main.js"
   },
   "devDependencies": {
      "@types/node": "^8.0.29",
      "@typescript-eslint/eslint-plugin": "^3.4.0",
      "@typescript-eslint/parser": "^3.4.0",
      "electron": "^9.4.0",
      "eslint": "^7.3.1",
      "mysql": "^2.14.1",
      "reflect-metadata": "^0.1.10",
      "sqlite3": "^5.0.2",
      "ts-node": "^3.3.0",
      "typeorm": "^0.2.32",
      "typescript": "^3.9.5"
   }
}

tsc在终端中使用没有任何错误,同样tsc --module commonjs --target esnext也可以正常工作。

如果我然后使用electron ./dist/main.js我会收到以下错误:

typeorm_1.createConnection().then(async (connection) => {
                                        ^
SyntaxError: Unexpected token (
    at Object.exports.runInThisContext (vm.js:76:16)
    at Module._compile (module.js:528:28)
    at Object.Module._extensions..js (module.js:565:10)
    at Module.load (module.js:473:32)
    at tryModuleLoad (module.js:432:12)
    at Function.Module._load (module.js:424:3)
    at loadApplicationPackage (...\npm\node_modules\electron-prebuilt\dist\resources\default_app.asar\main.js:280:12)
    at Object.<anonymous> (...\npm\node_modules\electron-prebuilt\dist\resources\default_app.asar\main.js:322:5)
    at Module._compile (module.js:556:32)
    at Object.Module._extensions..js (module.js:565:10)

如果我按照电子示例的建议使用npm run build && electron ./dist/main.js( npm start) 命令,则会收到以下错误:

import { Entity, PrimaryGeneratedColumn, Column, ManyToOne, OneToMany } from "typeorm";      
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at Module._compile (internal/modules/cjs/loader.js:895:18)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1004:10)
    at Module.load (internal/modules/cjs/loader.js:815:32)
    at Module._load (internal/modules/cjs/loader.js:727:14)
    at Function.Module._load (electron/js2c/asar.js:769:28)
    at Module.require (internal/modules/cjs/loader.js:852:19)
    at require (internal/modules/cjs/helpers.js:74:18)
    at {myappfolder}\node_modules\typeorm\util\DirectoryExportedClassesLoader.js:42:39
    at Array.map (<anonymous>)
    at Object.importClassesFromDirectories ({myappfolder}\node_modules\typeorm\util\DirectoryExportedClassesLoader.js:42:10)

在这两种情况下,程序/终端都会挂起,直到我按下ctrl+C(如果相关)

作为额外信息(如果需要):

我完全不知道如何解决这个问题,甚至不知道是什么原因造成的......所以任何帮助将不胜感激!

标签: javascriptnode.jstypescriptelectrontypeorm

解决方案


推荐阅读