gpt4 book ai didi

typescript - 使用 webpack 访问 TypeScript 全局变量

转载 作者:搜寻专家 更新时间:2023-10-30 21:57:51 25 4
gpt4 key购买 nike

我是 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();
});
}
}

当我尝试访问时,比如说 templates , 来自 Router类,它是未定义的。我有declare var templates在我的 Router.ts文件。我尝试了 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

此刻我有点迷茫。访问这些全局对象的最佳方式是什么?

最佳答案

您可以将您的应用程序编写为 Node.js 应用程序,然后使用 WebPack 创建一个包。

这是一个简单的例子。我假设所有输入文件都在一个目录中。应安装 webpackwebpack-clits-loadertypescript 包。

全局变量

export let foo = null;
export let bar = null;

索引.ts

import * as globals from "./globals";

globals.foo = "foo";
globals.bar = "bar";

console.log(globals);

tsconfig.json

{
"compilerOptions": {
"target": "esnext",
"module": "commonjs"
}
}

webpack.config.js

let path = require("path");

module.exports = {
entry: "./index.ts",
module: {
rules: [
{
test: /\.tsx?$/,
use: "ts-loader",
exclude: /node_modules/
}
]
},
resolve: {
extensions: [".tsx", ".ts", ".js"]
},
output: {
path: path.resolve(__dirname, "scripts"),
filename: "bundle.js"
},
mode: "development"
};

关于typescript - 使用 webpack 访问 TypeScript 全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51480053/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com