Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correct syntax to import constants in ES6

Given the following modules, how do I import the constants module and avoid having the default property included:

// constants.es6
export default {
    foo: 'foo',
    bar: 'bar'
}

// anotherModule.es6
import * as constants from './constants';

results in constants.default.foo

I can't seem to get the syntax correct to end up with constants.foo

like image 296
Samuel Goldenbaum Avatar asked Aug 28 '18 00:08

Samuel Goldenbaum


People also ask

Which is the correct syntax to declare a constant in JavaScript?

Below is the syntax mentioned: const <name of the variable> = value; Naming a constant in JavaScript has some rules for naming a variable, keeping intact the const keyword, and global constants. If in case the keyword 'const' is removed, the identifier is represented as a variable.

What is const in ES6?

ES6 introduced the const keyword, which is used to define a new variable in JavaScript. Generally, the var keyword is used to declare a JavaScript variable. Const is another keyword to declare a variable when you do not want to change the value of that variable for the whole program.

How do I import HTML into ES6?

The Current ES Modules Landscape Safari, Chrome, Firefox and Edge all support the ES6 Modules import syntax. Here's what they look like. Simply add type="module" to your script tags and the browser will load them as ES Modules. The browser will follow all import paths, downloading and executing each module only once.


1 Answers

import constants from './constants'

console.log(constants.foo, constants.bar)

If you would like to import the constants directly from ./constants

constants.js:
export const foo = 'foo'
export const bar = 'bar'

anotherModule.js:
import {foo, bar} from './constants'

console.log(foo,bar)
like image 137
nbwoodward Avatar answered Sep 22 '22 19:09

nbwoodward