[英]I am getting “Uncaught ReferenceError: angular is not defined” when using typescript
[英]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.