31

I am converting some ES5 code to ES6.

I have the following line somewhere in the file StatesComponent.js

const STATES = require('../data/states.js');

I am using jspm and it doesn't support require, so I would like to use ES6 import syntax instead.

The states.js file contains the following:

exports.AU = [
    { value: 'australian-capital-territory', label: 'Australian Capital Territory', className: 'State-ACT' },
    { value: 'new-south-wales', label: 'New South Wales', className: 'State-NSW' },
    { value: 'victoria', label: 'Victoria', className: 'State-Vic' },

];

exports.US = [
    { value: 'AL', label: 'Alabama', disabled: true },
    { value: 'AK', label: 'Alaska' },
    { value: 'AS', label: 'American Samoa' },
];

STATES variable is being used as var options = STATES[this.state.country];

How do I change the format of the json in states.js such that I can `import' it?

i.e import STATES from '../data/states'

2
  • 2
    Try import * as STATES from '../data/states.js'; Jan 12, 2016 at 10:31
  • 1
    Just for your information: This is not JSON. These are JavaScript literal objects.
    – RoToRa
    Jan 12, 2016 at 12:42

1 Answer 1

55

Not sure if you got the answer to this already but you can export it as:-

export default {
  STATES: {
    'AU' : {...},
    'US' : {...}
  }
};

to which you can import as:-

import STATES from 'states';

or

var STATES = {};
STATES.AU = {...};
STATES.US = {...};
export STATES;

to which you can import as:-

import { STATES } from 'states';

Notice the difference between one that uses default and one that doesn't. With default you can export any javascript expression and during import you can use whatever identifier and it will be defaulted to that default expression. You could also have done

import whatever from 'states';

and whatever would get the value of an object that we assigned to default.

In contrast, when you don't export default expression, export exports it as an part of object which is why you had to use

import {STATES}

In this case you HAVE to use the right literal name for import to work or else import will not be able to understand what you're trying to import. Also, note that it's using object destructuring to import the right value.

And like @AlexanderT said, there are ways to import as * too, in fact there are various ways to import and export but I hope I explained the core concept of how this import/export works.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.