In Nodejs I have a page called variables.js
which looks something like this:
exports.var1= 'a';
exports.var2= 'b';
This file holds variables I use within in my application all in one place.
Then inside of another page I call this page using:
var variables= require('./variables');
Now I have access to the variable sin that page by using it like this for example:
alert(variables.var1);
I would like to do the same thing inside of angular2 (typescript). I have tried to play with exports and imports but I can't get it to work. How can I do this inside of angular2 using typescript?
To import a variable from another file in TypeScript: Export the variable from file A , e.g. export const str = 'hello world' . Import the variable in file B as import { str } from './another-file' .
The export = syntax specifies a single object that is exported from the module. This can be a class, interface, namespace, function, or enum. When exporting a module using export = , TypeScript-specific import module = require("module") must be used to import the module.
To export a constant in TypeScript, we can use the export keyword. export const adminUser = { //... }; to export the adminUser constant.
variables.ts
export var var1:string = 'a';
export var var2:string = 'b';
other-file.ts
import {var1, var2} from './variables';
alert(var1);
or
import * as vars from './variables';
alert(vars.var1);
See also Barrel
at https://angular.io/guide/glossary#barrel
have tried to play with exports and imports but I can't get it to work. How can I do this inside of angular2 using typescript?
Just use the export
keyword and import
keyword. This is just ES6 and magically works with TypeScript ;) 🌹
export var1 = 'a'
import {var1} from './variables';
TypeScript modules are covered here : https://basarat.gitbooks.io/typescript/content/docs/project/modules.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With