89

I want to open 'file1.ts' and write:

export var arr = [1,2,3];

and open another file, let's say 'file2.ts' and access directly to 'arr' in file1.ts:

I do it by:

import {arr} from './file1';

However, when I want to access 'arr', I can't just write 'arr', but I have to write 'arr.arr'. The first one is for the module name. How do I access directly an exported variable name?

CrazySynthax
  • 13,662
  • 34
  • 99
  • 183
  • 1
    export [1, 2, 3] ? – yBrodsky Mar 01 '17 at 19:53
  • 5
    Ummm. No. If you import the way you posted then `arr` is the array. Only if you import it like this: `import * as arr from "./file1"` then you'll need to use it like `arr.arr` – Nitzan Tomer Mar 01 '17 at 20:04
  • 1
    Well, that's how it is supposed to be, as stated in [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import) and the [typescript docs](https://www.typescriptlang.org/docs/handbook/modules.html#import). If it's not working for you then you're probably doing something else. Your code works just fine for me where `arr` is the array without the need to use `arr.arr`. – Nitzan Tomer Mar 01 '17 at 22:50

2 Answers2

139

There are two different types of export, named and default.

You can have multiple named exports per module but only one default export.

For a named export you can try something like:

// ./file1.ts
const arr = [1,2,3];
export { arr };

Then to import you could use the original statement:

// ./file2.ts
import { arr } from "./file1";
console.log(arr.length); // 3

This will get around the need for arr.arr you mentioned.

How do pirates know that they are pirates? They think, therefore they ARR!!

Kieran
  • 17,572
  • 7
  • 45
  • 53
65

If you do:

var arr = [1,2,3];
export default arr;

...

import arr from './file1';

Then it should work

Mikael Gidmark
  • 1,303
  • 9
  • 18