Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

javascript - How to import everything exported from a file with ES2015 syntax? Is there a wildcard?

With ES2015 syntax, we have the new import syntax, and I've been trying to figure out how to import everything exported from one file into another, without having it wrapped in an object, ie. available as if they were defined in the same file.

So, essentially, this:

// constants.js

const MYAPP_BAR = 'bar'
const MYAPP_FOO = 'foo'
// reducers.js

import * from './constants'

console.log(MYAPP_FOO)

This does not work, at least according to my Babel/Webpack setup, this syntax is not valid.

Alternatives

This works (but is long and annoying if you need more than a couple of things imported):

// reducers.js

import { MYAPP_BAR, MYAPP_FOO } from './constants'

console.log(MYAPP_FOO)

As does this (but it wraps the consts in an object):

// reducers.js

import * as consts from './constants'

console.log(consts.MYAPP_FOO)

Is there a syntax for the first variant, or do you have to either import each thing by name, or use the wrapper object?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You cannot import all variables by wildcard for the first variant because it causes clashing variables if you have it with the same name in different files.

//a.js
export const MY_VAR = 1;

//b.js
export const MY_VAR = 2;


//index.js
import * from './a.js';
import * from './b.js';

console.log(MY_VAR); // which value should be there?

Because here we can't resolve the actual value of MY_VAR, this kind of import is not possible.

For your case, if you have a lot of values to import, will be better to export them all as object:

// reducers.js

import * as constants from './constants'

console.log(constants.MYAPP_FOO)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...