Reputation: 1653
I'm new to webpack and am in the process of converting a medium sized TypeScript app (without framework) over to using it. I have some global variables in my main.ts
file that I can't access.
// 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();
});
}
}
When I try and access, say, templates
, from the Router
class, it is undefined.
I have declare var templates
in my Router.ts
file. I tried the suggestions in this answer & this answer (putting them in a globals.ts
/globals.js
file, and using ProvidePlugin
but without success)
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;
I get the error TS2304: Cannot find name 'globals'.
If I then add in import * as globals from "./globals"
it compiles but I get the following error in the browser console - Uncaught TypeError: Cannot set property config of #<Object> which has only a getter
I'm a little lost at the moment. What's the best way to access these global objects?
Upvotes: 2
Views: 4312
Reputation: 7536
You can write your application as a Node.js one and then use WebPack to create a bundle.
Here's a simple example. I assume all input files are in one directory.
webpack
, webpack-cli
, ts-loader
, typescript
packages should be installed.
globals.ts
export let foo = null;
export let bar = null;
index.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"
};
Upvotes: 1