Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

angular2(typescript) export variables from another file

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?

like image 897
user2924127 Avatar asked Jun 06 '16 05:06

user2924127


People also ask

How do I import a variable from another file in 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' .

What is export {} in TypeScript?

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.

How do I export a TypeScript Const?

To export a constant in TypeScript, we can use the export keyword. export const adminUser = { //... }; to export the adminUser constant.


2 Answers

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

like image 146
Günter Zöchbauer Avatar answered Sep 18 '22 08:09

Günter Zöchbauer


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:

export var1 = 'a'

Import:

import {var1} from './variables';

More

TypeScript modules are covered here : https://basarat.gitbooks.io/typescript/content/docs/project/modules.html

like image 37
basarat Avatar answered Sep 20 '22 08:09

basarat