0

In the following, is values a normal object in file-2.js?

// file-1.js
export {
    FOO,
    BAR
} from '~/my-values';

// file-2.js
import * as values from '~/file-1';

// what is `values` here? an object instance?

I ask because I want to use something like values.hasOwnProperty('FOO') and rollup raised the following error:

'hasOwnProperty' is not exported by 'file-1.js'

Side question: is there a convenient way to test code using the import and export keywords? To the best of my knowledge Chrome dev tools to not support them in snippets.

Ben Aston
  • 53,718
  • 65
  • 205
  • 331

2 Answers2

3

These are module namespace exotic objects. They being exotic means that they are not exactly normal objects (they have different internals).

They also do not have Object.prototype on their prototype chain, so you can't use hasOwnProperty but you should be able to use it with Function.prototype.call or Function.prototype.apply since they do have an internal method for [[ GetOwnProperty ]]

Object.prototype.hasOwnProperty.call(values, 'FOO');

You can also use Reflect.has on it.

Reflect.has(values, 'FOO');

Also since the prototype is null you can pretty much just use in too:

'FOO' in values
MinusFour
  • 13,913
  • 3
  • 30
  • 39
0

Lets say X.js is the following:

export const t = 0;
export const t2 = 4;
export default w = -1;
var w3 = -9;

When you do import * as Y from X;

Basically you get all the exports from that file and you get to them by calling X.some var that has export. For example:

var t = X.t; // local t will be equal 0.

You cannot get the vars from X file without export (as they are locally set there.

You could also import the mentioned above code like this for example, by getting the values you need.

import {t} from X.js
var local_t = t; // local_t is set to 3

The export default means that if you import the file without saying with const or * you will get the default export value. For example:

import something from X.js;
var _local = something; //_local equals -1

Hope it helps.

Matt
  • 354
  • 1
  • 5
  • Thank you. Can I enumerate the properties ("exports") of a module? I want to use something like `module.hasOwnProperty('moduleName');` – Ben Aston Oct 26 '17 at 12:59