簡體   English   中英

未捕獲的 ReferenceError:使用 TypeScript + Webpack 時未定義 foo

[英]Uncaught ReferenceError: foo is not defined when using TypeScript + Webpack

如果我只使用 JavaScript,我的 Chrome 擴展程序就可以正常工作。

當我嘗試 TypeScript + Webpack 時,我面臨的問題是找不到 function foo

未捕獲的 ReferenceError:未定義 foo

manifest.json:

    "content_scripts":
    [
        {
            "js": ["global.js", "content.js"],
            "matches": ["https://*.my-domain.com/*"],
            "run_at": "document_end"
        }
    ],

內容.ts:

console.log("content.js");

let afterDOMLoaded = () =>
{
    foo()
    .then((result) => console.log(result))
    .catch((error) => console.error(error));
}

if (document.readyState === 'loading')
{
    document.addEventListener('DOMContentLoaded', afterDOMLoaded);
}
else
{
    afterDOMLoaded();
}

全球.js:

console.log("global.js");

let foo = async () =>
{
    await something();
}

tsconfig.json:

{
    "compilerOptions": {
        "outDir": "./dist",
        "allowJs": true,
        "target": "ES6"
    },
    "include": [
        "./src/**/*"
    ]
}

webpack.config.js:

const path = require("path");
const glob = require("glob");
const CopyPlugin = require("copy-webpack-plugin");

module.exports =
{
    entry: glob.sync('./src/**/*.ts').reduce(function(obj, el)
    {
        obj[path.parse(el).name] = el;
        return obj;
    }, {}),

    output:
    {
        filename: "[name].js",
        path: path.resolve(__dirname, "dist")
    },

    module:
    {
        rules: [
            { test: /\.ts?$/, loader: "ts-loader" }
        ]
    },

    plugins: [
        new CopyPlugin(
        {
            patterns: [
            {
                from: "**",
                to: path.resolve(__dirname, "dist"),
                context: path.resolve(__dirname, "src"),
                globOptions: { ignore: ["**/*.ts"] },
                force: true
            }]
        })
    ],
    
    optimization:
    {
        minimize: false,
        splitChunks: 
        {
            chunks: "all"
        }
    }
}

我可以看到加載腳本的順序也是正確的,如 console.log 所示:

global.js
content.js

如果我在 content.ts 中定義foo ,就在頂部,那么一切正常。

所以我不知道問題出在哪里,webpack 還是 typescript?

Webpack wraps each "module" (a file is itself a module) in its own function scope, so the let foo variable is block scoped and no longer accessible in "global" scope by the content module.

使用export / import語法(畢竟,這很可能是使用捆綁器的原因),或者將其放在全局 scope 上(無變量關鍵字)。 但是 IIRC,在擴展中使用全局 scope 可能會干擾呈現的 web 頁面?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM