【问题标题】:Electron - importing exporting modulesElectron - 导入导出模块
【发布时间】:2022-12-17 01:43:17
【问题描述】:

我正在做一个电子反应打字稿应用程序。 我想预加载一个数据库 (sqlite) 函数调用,以便我可以在渲染器 (react) 环境中使用该方法。 为此,我在另一个名为testmgr.ts 的文件中准备了函数

const dbmgr = require('./dbmgr'); //dbmgr is the file that prepares the database (its file on the pc)
const dbTest = dbmgr.db;

function getSomeNames() {
    const query = 'SELECT * FROM test';
    const stmt = dbTest.prepare(query);
    const res = stmt.all();
    return res;
}
export {};

现在在 preload.ts 文件中,我有这个:

const testMgr = require("./testmgr.ts");
const { contextBridge } = require("electron");

const getNames = () => {
  return testMgr.getSomeNames();
};
contextBridge.exposeInMainWorld("api", { getNames: getNames });`

编译时,我在控制台中收到以下错误:

语法错误:意外的令牌“导出”

如果我从文件 testmgr.ts 中删除 export {},我将收到此错误

testmgr.ts' 不能在 '--isolatedModules' 下编译,因为它被认为是全局脚本文件。添加导入、导出或空的“export {}”语句以使其成为模块。

我需要做什么才能避免这个问题?

【问题讨论】:

  • 你有没有找到解决这个问题的方法?

标签: node.js typescript module electron export


【解决方案1】:

我遇到了完全相同的问题。发生这种情况是因为我正在编写一些要用节点执行的打字稿(即ts-node scripts/myscript.ts),但是在同一个回购协议中已经有一些要从浏览器执行的打字稿。所以目录的根目录下已经有一个tsconfig.json文件。

它看起来像这样:

{
  "compilerOptions": {
    "target": "es5",
    "lib": ["dom", "dom.iterable", "esnext"],
    "allowJs": true,
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "noFallthroughCasesInSwitch": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "baseUrl": "src",
    "noImplicitAny": false,
    "jsx": "react-jsx"
  },
  "include": ["src"]
}

当我删除 "module": "esnext", 然后命令ts-node scripts/myscript.ts 开始工作。

从存储库根目录下的 tsconfig.json 文件中删除这一行并不是最好的解决方案,因为那样会破坏所有已经编写好的在浏览器中执行的打字稿代码。

由于我的打字稿代码将由位于单独子文件夹中的节点执行,我只是将 tsconfig.json 文件复制到该子文件夹中并删除了有问题的行 ( "module": "esnext",)。这在不影响浏览器执行的代码的情况下修复了它。现在运行命令ts-node scripts/myscript.ts 工作正常。它必须用它在 scripts 文件夹中找到的那个覆盖 repo 根目录下的 tsconfig.json。

【讨论】:

    猜你喜欢
    • 2018-12-09
    • 1970-01-01
    • 2021-09-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-06
    • 2015-05-08
    • 2021-08-21
    相关资源
    最近更新 更多