12

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?

2 Answers 2

24

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

Sign up to request clarification or add additional context in comments.

6 Comments

When I try import "../variables" as vars; I get the error: Error TS1005: ';' expected. Ther eis a semicolon so I am not sure what it is complaining about?
It is now saying my ./variables.ts is not a module
are both files in the same directory?
Yes they are in the exact same folder.
Sorry, another error. I missed var after export. Working Plunker example
|
3

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.