admin管理员组文章数量:1431530
How do I export as default multiple imported modules?
I could do something like the code below, but if I were to import multiple files the boilerplate could grow quickly. Is there a shorthand way to achieve this?
import Foo from './Foo'
import Bar from './Bar'
//...
export default {
Foo,
Bar
//...
}
Note that in my code above, I'm not exporting multiple values. I'm importing multiple values, accumulating them, and exporting them as a single object. I intend to refer to the reexported values by Baz.Foo
or Baz.Bar
, assuming the code above is Baz.js
.
How do I export as default multiple imported modules?
I could do something like the code below, but if I were to import multiple files the boilerplate could grow quickly. Is there a shorthand way to achieve this?
import Foo from './Foo'
import Bar from './Bar'
//...
export default {
Foo,
Bar
//...
}
Note that in my code above, I'm not exporting multiple values. I'm importing multiple values, accumulating them, and exporting them as a single object. I intend to refer to the reexported values by Baz.Foo
or Baz.Bar
, assuming the code above is Baz.js
.
- Read this page: stackoverflow./questions/38340500/… – R.tbr Commented Jul 25, 2019 at 8:22
- Finally found a shorthand way that works with default exports. I'm using it in my application now :) – dandeto Commented Nov 5, 2019 at 6:24
4 Answers
Reset to default 2Instead of accumulating boilerplate from importing lots of files to simply re-export them, you can do this:
// In library.js
export { default as Foo } from "./Foo.js";
export { default as Bar } from "./Bar.js";
// In new_file.js
import { Foo, Bar } from "../lib/library.js"
var phooey = new Foo();
This selects whatever you are exporting as default and gives it an alias.
export default
is not meant to be used with multiple exports: https://developer.mozilla/en-US/docs/web/javascript/reference/statements/export#Using_the_default_export
If we want to export a single value or to have a fallback value for your module, you could use a default export
You should use named exports like this:
export {
Foo,
Bar
//...
}
In es6 there are two types of exports named and default exports.
Since you want to export default assign all the modules to an object like below
Const modules = {Foo, Bar }
export default modules;
Then in other files use like below
Import modules from 'path/yourfiles'
modules.Foo.xxx
modules.Bar.xxx
import * as name from "module-name";
This will be a great fit for your application. And when you want to access the object, you can use
name.object = ...;
And let me know, if it is right.
本文标签: javascriptExport as default multiple imported modulesStack Overflow
版权声明:本文标题:javascript - Export as default multiple imported modules - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745558746a2663343.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论