【发布时间】:2018-07-23 13:30:55
【问题描述】:
我是 webpack 的新手,正在将一个中型 TypeScript 应用程序(无框架)转换为使用它。我的main.ts 文件中有一些无法访问的全局变量。
// Global variables
let templates;
let router;
let config;
$(document).ready(() => {
$.get("/config", (data) => {
// Create our config object
config = new Config(data);
// Load all templates
templates = new Templates();
templates.ready(() => {
router = new Router();
router.initialize();
});
}
}
当我尝试从Router 类访问templates 时,它是未定义的。
我的Router.ts 文件中有declare var templates。我尝试了this answer 和this answer 中的建议(将它们放在globals.ts/globals.js 文件中,并使用ProvidePlugin 但没有成功)
webpack.config.js -
plugins: [
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
globals: path.resolve(__dirname, "./globals"),
}),
],
main.ts -
$(document).ready(() => {
$.get("/config", (data) => {
// Create our config object
globals.config = new Config(data);
// Load all templates
globals.templates = new Templates();
globals.templates.ready(() => {
globals.router = new Router();
globals.router.initialize();
});
}
}
globals.ts/js -
export let templates, pageManager, config;
我收到错误TS2304: Cannot find name 'globals'.
如果我随后添加 import * as globals from "./globals" 它会编译但我在浏览器控制台中收到以下错误 - Uncaught TypeError: Cannot set property config of #<Object> which has only a getter
我现在有点迷茫。访问这些全局对象的最佳方式是什么?
【问题讨论】:
标签: typescript webpack