moduleResolution:nodeNext“禁用”我的 chrome 扩展程序的上下文菜单

moduleResolution: nodeNext "disables" the context menu of my chrome extension

提问人:jacob040 提问时间:11/15/2023 更新时间:11/15/2023 访问量:31

问:

我目前正在编写一个个人 chrome 扩展程序,我可以通过突出显示文本、右键单击并通过上下文菜单翻译文本来翻译文本。

我让上下文菜单在没有实际翻译功能的情况下工作。 但是,当我开始使用deepl-node API实现上述功能时,我收到了此错误:

“找不到模块'deepl-node'。您的意思是将“moduleResolution”选项设置为“nodenext”,还是将别名添加到“paths”选项?TS(2792)”

因此,我在 tsconfig.json 中将我的模块从 ESNext 更改为 NodeNext,并添加了 moduleResolution 语句并将其设置为 NodeNext。

这解决了我的 API 问题,但它从上下文菜单中删除了我的菜单选择。我不知道为什么,在网上找不到任何解释。

这是我tsconfig.json:

{
  "compilerOptions": {
    "target": "ES2020",
    "module": "NodeNext",
    "moduleResolution":"NodeNext",
    "strict": true,

  },
  "include": ["public/background.ts"],
}

这是我的背景.js

import * as deepl from 'deepl-node';
const authKey = "censored"; //REMEMBER TO HIDE
const translator = new deepl.Translator(authKey);

chrome.contextMenus.create({
    id: "1",
    title: "Translate \"%s\"",
    contexts: ["selection"],
});

console.log("Context menus created yo!");
// Store the tab ID of the newly created tab
let newTabId = null;
// Listen for the creation of a new tab
chrome.tabs.onCreated.addListener((tab) => {
    // Update the newTabId variable when a new tab is created
    newTabId = tab.id;
});

chrome.contextMenus.onClicked.addListener((info, tab) => {
    if (info.menuItemId === "1") {
        // Perform the fake translation logic
        const toTranslate = info.selectionText;
        const translatedText = Translate(toTranslate);
        // Now, open a new tab
        chrome.tabs.create({
            url: chrome.runtime.getURL("index.html"),
            active: true,
        });
        // Wait for the new tab to be created and then send the message to it
        const checkNewTabInterval = setInterval(() => {
            if (newTabId !== null) {
                // Send the message to the new tab using the unique task ID
                chrome.tabs.sendMessage(newTabId, { action: "updateTranslation", text: translatedText, taskId: newTabId }, () => {
                    // Callback function, executed once the message is sent
                    console.log("Message sent!");
                });
                // Clear the interval as the message has been sent
                clearInterval(checkNewTabInterval);
            }
        }, 100); // Adjust the interval as needed
    }
});

function Translate(TextToTranslate) {
    
    const translation = translator.translateText(TextToTranslate, null, 'es'); //Null means source language will be autodetected
    
    return translation;
}

javascript typescript google-chrome-extension svelte deepl

评论

0赞 wOxxOm 11/15/2023
在页面中检查扩展 chrome://extensions 错误。如果没有,请使用 devtools 设置断点并调试代码。
0赞 5ar 11/15/2023
不确定解决方案,但如果您更改了模块选项,则您刚刚更改了导入的工作方式,并且代码可能在导入或使用导入时中断(因为它可能未定义)。尝试使用 require 而不是 import,以防该包现在被视为 CJS 模块。

答: 暂无答案