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'
To export package JSON first open a package, find the Import/Export dropdown and press the Export button. After that, the browser will start a download. The exported JSON file is formatted so it will be easy to track the difference between such files.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With