Javascript export default and import - javascript

I have the following code:
const API1 = new API({
...
})
const API2 = new API({
...
})
export default { API1, API2 }
I need to import like this:
import API1 from '/lib/api'
API1.get()...
But it doesn't work.
I don't want to do this:
import blah from '/lib/api'
blah.API1.get()...
How can I solve this ?
Thanks.

If you need to export multiple items, and don't want to have to create two variables in the consuming module (one for the default import - the object, and another for the API1 property), your only other option is to change the default export to a named export, allowing you to import just one particular named property:
const API1 = new API({
...
})
const API2 = new API({
...
})
export { API1, API2 }
and
import { API1 } from '/lib/api'
API1.get()...
The export { syntax indicates that the export is named, rather than default, and the import { syntax indicates that you're importing a named import, rather than a default import.
(It looks a lot like destructuring, and it's a little bit similar, but it's not the same)

Since you're default exporting an object you need to access individual property to access there methods, Instead you can use named exports
// exporting values
export const API1 = new API({
...
})
export const API2 = new API({
...
})
// Importing values
import { API1 } from '/lib/api'
API1.get()...

Related

Multiple exports from react.js file

I have a react.js file MyComponent that has this at the end:
module.exports = MyComponent, where MyComponent is a function defined in the file.
What if I want to export ANOTHER function: MyHelperComponent from the same file, so that another react component from another react.js file may use MyHelperComponent directly ?
So my question is: how do I export a function that is not the 'main' component of the module ?
You can only export one value from a module.
If you need to use multiple values outside it, then you need to group them somehow. Typically you would put them in an object and then export that object.
module.exports = { MyComponent, MyHelperComponent };
And then:
const MyComponent = require("./mymodule.js").MyComponent;
const MyHelperComponent = require("./mymodule.js").MyHelperComponent;
or
const mymodule = require("./mymodule.js")
const MyComponent = mymodule.MyComponent;
const MyHelperComponent = mymodule.MyHelperComponent;
or
const {MyComponent, MyHelperComponent} = require("./mymodule.js");
That said, it is usual to structure code on a one-component-per-module basis, so you might want to rethink doing this in the first place.
You can do it like this:
//...function defs here
MyComponent.helper = MyHelperComponent
module.exports = MyComponent
And then just access MyComponent.helper(args) to call the helper function.
You can export like this: export { component1, component2 }
And use like this: import { component1, component2 } from './url'
or
import * as components from './url'
<components.component1 />
Hope helpful...

How to Export Variables with a Dynamic Names

I have a components folder in nuxt.js
/components/atoms/
and inside that folder I have an index.js to export all components dynamically
const req = require.context('./', true, /\.vue$/)
const components = {}
req.keys().forEach(fileName => {
const componentName = fileName.replace(/^.+\/([^/]+)\.vue/, '$1')
components[componentName] = req(fileName).default
})
export const { ButtonStyled, TextLead, InputSearch } = components
so I can import perfectly as I wish
import { ButtonStyled } from "#/components/atoms"
the problem is that I am defining the variables to be exported statically, fixed, so for each created component I would need to add another variable manually
I need to dynamically export the variable name
Example:
DynamicCreation = ['ButtonStyled', 'TextLead', 'InputSearch']
export const { DynamicCreation } = components
// output -> export const { ButtonStyled, TextLead,InputSearch } = components
I need to export the name of already unstructured variables
Note: I can not use this export default components because I can not import like this import { ButtonStyled } from "#/components/atoms"
You should be able to do it like this:
export default components
Then in your file where you want to use the components:
import * as components from '#/components/atoms'
Then when you need to use the components in your Vue files, you need to map them:
#Component({
components: {
ButtonStyled: components.ButtonStyled
}
})
And now you have:
<ButtonStyled></ButtonStyled>
You can make something like this way, check if is what do you need.
Create a file to import a conjunct of components: allComponents.js
export default {
componentOne: require('./passToOneComponent.js');
componentTwo: require('./passToOneComponent.js');
componentThree: require('./passToOneComponent.js');
}
After in index.js export the allComponents.js with the name that you wish:
export {default as SomeName } from 'allComponents.js';
So in the final file, you can make something like:
import { SomeName } from 'index.js';
SomeName.componentOne();
I created a library that does this type of export, anyone who wants can install via npm
I created a Webpack Plugin that makes named exports from a component, maybe this helps other people
Weback Plugin - named-exports

Export of a class instance in Javascript

I was looking at this code where a class instance is exported in a little bit weird way.
Providing a snipped. It is exported as follows:
class RegisterStore {
#observable success = false
#observable failure = false
#observable errors = {}
...
}
export default new RegisterStore()
export { RegisterStore }
And it is imported as follows in index.js:
import registerStore from './stores/RegisterStore'
...
const stores = {
registerStore
...
}
Why are there two exports at the end of the first code? Is
export default new RegisterStore() AND
const NewRegisterStore = new RegisterStore(); export default NewRegisterStore are equivalent?
No export default new RegisterStore() and export { RegisterStore } are not equal. In export { RegisterStore } you are exporting the class as a part of an export object while in export default new RegisterStore() you are exporting instance of class.
Further. export default new RegisterStore() should be enough to work fine. Exporting again line is useless until you dont want to import multiple variables from the same file. In that case it would be like:
export new RegisterStore();
export const anotherVariable = "TESTTEST";
and import like:
import {RegisterStore, anotherVariable} from './stores/RegisterStore';
Further to your last query:
NO
export default new RegisterStore() AND
export default const RegisterStore = new RegisterStore() are equivalent?
are not equivalent too.
Firstly export default const RegisterStore = new RegisterStore() throws error because RegisterStore is already declared as class and you are again declaring it with const.
Secondly:
export default const NewRegisterStore = new RegisterStore()
is also wrong because default exports have to be either exported as anonymous or the variables have to be declared first before exporting.
For your example it should be like:
let NewRegisterStore; export default NewRegisterStore = new RegisterStore();
So:
export default new RegisterStore() AND
let NewRegisterStore; export default NewRegisterStore = new RegisterStore(); are equivalent
Please read more about "named export" and "export default" here

Failing to import properties of a module

I have a module A that is like
const defaults = {
something: {...},
somethingElse : {...}
}
export { defaults as default };
And then I am importing like
import * as mod, { something } from 'moduleA';
mod is correctly an object that has the two declared properties, but { something } is undefined.
Any idea what can be the reason?
[With the module as in the question] I am importing like
import * as mod, { something } from 'moduleA';
but something is undefined
But you don't have an export with the name something in your module. There only is a default-export that contains an object. You would need to do
import mod from 'moduleA';
const { something } = mod;
I have a module A that is like
const defaults = {
something: {...},
somethingElse : {...}
}
export { defaults as default };
But you really shouldn't do that anyway. Exporting "singleton" objects that act like a namespace is an antipattern in ES6 modules. You should use named exports instead:
export const something = {...};
export const somethingElse = {...};
With this, your original attempt at importing the module would have worked.
If you want to be able to access named exports in your import, you have to export them directly:
const defaults = {
something: {...},
somethingElse : {...}
}
export {
defaults as default,
defaults.something as something,
defaults.somethingElse as somethingElse
};
Alternatively you could use destructuring for the export of something and somethingElse:
export const { something, somethingElse} = defaults;
And then import it like you did:
import * as mod, { something } from 'moduleA';
But: mod will now contain the props: defaults, something, somethingElse.
If you only wont the default (which equals your defaults):
import mod, { something } from 'moduleA';
You can learn more about the ES6 import and export syntax in Axel Rauschmayr's great blog post:
http://www.2ality.com/2014/09/es6-modules-final.html
import * as mod, { something } from 'moduleA';
The reason something is undefined is because when you: export { defaults as default }; you're exporting a member called default. When you export {apple, banana} you export a member apple and a member banana.
When you import something without specifying the members you want to import you import the member named default. When you do specify the members you wish to import, of course, you import those.
This is why although your code doesn't do what you intend, the following will:
const mod = { something: 'test'};
export { mod as default }; // same as export default mod;
and
import mod, {default as test} from './index'; // test and mod both have the same values
console.log(mod); // { something: 'test' }
console.log(test.something); // test
something is not exported from your module A, only the object defaults is.
So, to get something, you need to take it from what you imported.
import * as mod from 'moduleA';
const something = mod.something;
If you want to be able to import something like this : import {something} from 'moduleA', you will need to export it explicitely. For example:
export const something = {};
const somethingElse = {};
export default const defaults = {
something,
somethingElse
};

ES6 exporting/importing in index file

I am currently using ES6 in an React app via webpack/babel.
I am using index files to gather all components of a module and export them. Unfortunately, that looks like this:
import Comp1_ from './Comp1.jsx';
import Comp2_ from './Comp2.jsx';
import Comp3_ from './Comp3.jsx';
export const Comp1 = Comp1_;
export const Comp2 = Comp2_;
export const Comp3 = Comp3_;
So I can nicely import it from other places like this:
import { Comp1, Comp2, Comp3 } from './components';
Obviously that isn't a very nice solution, so I was wondering, if there was any other way. I don't seem to able to export the imported component directly.
You can easily re-export the default import:
export {default as Comp1} from './Comp1.jsx';
export {default as Comp2} from './Comp2.jsx';
export {default as Comp3} from './Comp3.jsx';
There also is a proposal for ES7 ES8 that will let you write export Comp1 from '…';.
Also, bear in mind that if you need to export multiple functions at once, like actions you can use
export * from './XThingActions';
Too late but I want to share the way that I resolve it.
Having model file which has two named export:
export { Schema, Model };
and having controller file which has the default export:
export default Controller;
I exposed in the index file in this way:
import { Schema, Model } from './model';
import Controller from './controller';
export { Schema, Model, Controller };
and assuming that I want import all of them:
import { Schema, Model, Controller } from '../../path/';
default export
// Default export (recommended)
export {default} from './module'
// Default export with alias
export {default as d1} from './module'
all export
// In >ES7, it could be
export * from './module'
// In >ES7, with alias
export * as d1 from './module'
function name export
// export by function names
export { funcName1, funcName2, …} from './module'
// export by aliases
export { funcName1 as f1, funcName2 as f2, …} from './module'
destructured object export
// export destructured object
export const { myVar, myFunction } = myObjectWithEverything
// export destructured object, with renaming
export const { v1: myVar, f1: myFunction } = myBigObject
with array
// it works with array as well
export const [ funcName1, funcName2 ] = myBigArray
More infos: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export
Folder structure:
components|
|_ Nave.js
|_Another.js
|_index.js
Nav.js comp inside components folder
export {Nav}
index.js in component folder
export {Nav} from './Nav';
export {Another} from './Another';
import anywhere
import {Nav, Another} from './components'
I've been searching for years how to export modules as both, named exports, and default exports in modular JavaScript. After tons of experimenting, the solution I found is quite simple and efficient.
// index.js
export { default as Client } from "./client/Client.js";
export { default as Events } from "./utils/Events.js";
// Or export named exports
export { Client } from "./client/Client.js";
export { Events } from "./utils/Events.js";
export * as default from "./index.js";
This would allow each exported module to be imported in two ways:
// script.js
import { Client } from "index.js";
new Client();
import module from "index.js";
new module.Client();
// You could also do this if you prefer to do so:
const { Client } = module;
You can mess around with this to have it suit your needs, but it works for me. Hope it helps!
What worked for me was adding the type keyword:
export type { Comp1, Comp2 } from './somewhere';
Install #babel/plugin-proposal-export-default-from via:
yarn add -D #babel/plugin-proposal-export-default-from
In your .babelrc.json or any of the Configuration File Types
module.exports = {
//...
plugins: [
'#babel/plugin-proposal-export-default-from'
]
//...
}
Now you can export directly from a file-path:
export Foo from './components/Foo'
export Bar from './components/Bar'
Good Luck...

Categories

Resources