Export multiple classes in ES6 modules - javascript

I'm trying to create a module that exports multiple ES6 classes. Let's say I have the following directory structure:
my/
└── module/
├── Foo.js
├── Bar.js
└── index.js
Foo.js and Bar.js each export a default ES6 class:
// Foo.js
export default class Foo {
// class definition
}
// Bar.js
export default class Bar {
// class definition
}
I currently have my index.js set up like this:
import Foo from './Foo';
import Bar from './Bar';
export default {
Foo,
Bar,
}
However, I am unable to import. I want to be able to do this, but the classes aren't found:
import {Foo, Bar} from 'my/module';
What is the correct way to export multiple classes in an ES6 module?

Try this in your code:
import Foo from './Foo';
import Bar from './Bar';
// without default
export {
Foo,
Bar,
}
Btw, you can also do it this way:
// bundle.js
export { default as Foo } from './Foo'
export { default as Bar } from './Bar'
export { default } from './Baz'
// and import somewhere..
import Baz, { Foo, Bar } from './bundle'
Using export
export const MyFunction = () => {}
export const MyFunction2 = () => {}
const Var = 1;
const Var2 = 2;
export {
Var,
Var2,
}
// Then import it this way
import {
MyFunction,
MyFunction2,
Var,
Var2,
} from './foo-bar-baz';
The difference with export default is that you can export something, and apply the name where you import it:
// export default
export default class UserClass {
constructor() {}
};
// import it
import User from './user'

Hope this helps:
// Export (file name: my-functions.js)
export const MyFunction1 = () => {}
export const MyFunction2 = () => {}
export const MyFunction3 = () => {}
// if using `eslint` (airbnb) then you will see warning, so do this:
const MyFunction1 = () => {}
const MyFunction2 = () => {}
const MyFunction3 = () => {}
export {MyFunction1, MyFunction2, MyFunction3};
// Import
import * as myFns from "./my-functions";
myFns.MyFunction1();
myFns.MyFunction2();
myFns.MyFunction3();
// OR Import it as Destructured
import { MyFunction1, MyFunction2, MyFunction3 } from "./my-functions";
// AND you can use it like below with brackets (Parentheses) if it's a function
// AND without brackets if it's not function (eg. variables, Objects or Arrays)
MyFunction1();
MyFunction2();

#webdeb's answer didn't work for me, I hit an unexpected token error when compiling ES6 with Babel, doing named default exports.
This worked for me, however:
// Foo.js
export default Foo
...
// bundle.js
export { default as Foo } from './Foo'
export { default as Bar } from './Bar'
...
// and import somewhere..
import { Foo, Bar } from './bundle'

// export in index.js
export { default as Foo } from './Foo';
export { default as Bar } from './Bar';
// then import both
import { Foo, Bar } from 'my/module';

For multiple classes in the same js file, extending Component from #wordpress/element, you can do that :
// classes.js
import { Component } from '#wordpress/element';
const Class1 = class extends Component {
}
const Class2 = class extends Component {
}
export { Class1, Class2 }
And import them in another js file :
import { Class1, Class2 } from './classes';

you can do.
export{className, className and so on}

For exporting the instances of the classes you can use this syntax:
// export index.js
const Foo = require('./my/module/foo');
const Bar = require('./my/module/bar');
module.exports = {
Foo : new Foo(),
Bar : new Bar()
};
// import and run method
const {Foo,Bar} = require('module_name');
Foo.test();

Related

"Element type is invalid: expected a string" in the definition of my main component: export const Autocomplete = (props) => {....}

I am new in react.
My main component is defined in the way:
import React from "react";
import { useState } from "react";
export const Autocomplete = (props) => {
return (
<div className="wrapper">
hello
</div>
);
};
I am getting this error:
Element type is invalid: expected a string (for built-in components)
or a class/function (for composite components) but got: undefined. You
likely forgot to export your component from the file it's defined in,
or you might have mixed up default and named imports.
this is my index.js
import { StrictMode } from "react";
import ReactDOM from "react-dom";
import App from "./App";
const rootElement = document.getElementById("root");
ReactDOM.render(
<StrictMode>
<App /> <!--my main component-->
</StrictMode>,
rootElement
);
what am I doing wrong? thanks
Answer
You've made your main component a named export named Autocomplete, but you are importing a default component called App.
Try this:
import { StrictMode } from "react";
import ReactDOM from "react-dom";
import { Autocomplete } from "./App";
const rootElement = document.getElementById("root");
ReactDOM.render(
<StrictMode>
<Autocomplete /> <!--my main component-->
</StrictMode>,
rootElement
);
Explaining Named vs Default Exports
There are two ways of exporting and each way requires you to import the exported member differently.
Named Export/Import
Named exports have to be imported using the same name as the exported member. The import will also have braces around the imported members. You can export multiple members from a single file.
foobar.js
export const foo = 'foo';
export const bar = 'bar';
const baz = 'baz';
// or
const foo = 'foo';
const bar = 'bar';
const baz = 'baz';
export {foo, bar};
main.js
import { foo, bar } from './foobar'
Default Export/Import
Default exports can be imported using any name you want. There will be no braces around the import. You can only default export a single member from a file.
foobar.js
export default {foo: '', bar: ''}; // directly exporting the value (an object), no variable declaration involved
// or
const foobar = {foo: '', bar: ''};
export default foobar;
main.js
import foobar from './foobar';
const foo = foobar.foo;
const bar = foobar.bar;
// or
import whatever from './foobar';
const foo = whatever.foo;
const bar = whatever.bar;
Named and Default Export/Import
You can also have both default and named exports from the same file. You may have seen this with React.
foobar.js
export const foo = 'foo';
export const bar = 'bar';
export default foobar = 'foobar';
main.js
import myFoobar, { foo, bar } from './foobar'
import React, { useState } from 'react';

import and export module in same file

Does anyone know of a better way to do this?
The goal: import, use, and export createLogger from the same file (application entry point).
WebStorm gives me a duplicate declaration warning.
import createLogger from './logger';
const logger = createLogger('namespace');
export { default as createLogger };
export { * as plugins } from './plugins';
export setup = () => {
// ...
logger.log('');
}
export start = async () => {
// ...
logger.log('');
}
To export multiple functions from the same file just do this:
import createLogger from './logger';
const logger = createLogger('namespace');
import plugins from './plugins';
import anotherLib from './anotherLib';
const setup = () => {
// ...
logger.log('');
}
const start = async () => {
// ...
logger.log('');
}
// export everything without default
export { plugins,
createLogger,
anotherLib,
setup,
start}
You can import them in another file after this is done.
Here's a sandbox to see how it works.
Have a look at this documentation about the export statement.

Export module class from another module

I have a module netmap that exports a default class NetMap:
export default class NetMap {...}
I have another module helloworld and I want to export (not as a default) the entire NetMap class so that another module can access NetMap by using:
import * as helloworld from 'helloworld'
const x = helloworld.NetMap()
Is this possible? What would the export of NetMap look like in the helloworld module?
netmap.js
export default class NetMap {
...
}
helloworld.js (usually called a barrel):
import NetMap from './netmap.js';
import Foo from '...';
import ...
export {
NetMap,
Foo,
...
};
Then, in another module:
import * as helloworld from './helloworld.js';
const x = new helloworld.NetMap();
But I personally prefer to use named imports/exports, so I would do it like this instead:
netmap.js
export class NetMap {
...
}
helloworld.js (usually called barrel):
export { NetMap } from './netmap.js';
export { Foo } from '...';
export { ...
Then, in another module:
import * as helloworld from './helloworld.js';
const x = new helloworld.NetMap();
Or:
import { NetMap } from './helloworld.js';
const x = new NetMap();
I think I can tell what you're trying to do, and it certainly seems possible. But do let me know if I misunderstood.
So you have your netMap file...
// netMap.js
class NetMap {
constructor(a,b) {
this.a = a
this.b = b
}
}
export default NetMap
then you have your helloworld file that uses netmap as well as maybe some other things....
// helloworld.js
const netMap = require('./netMap')
// import netMap from 'netMap'
const helloWorld = _ => console.log('hello world!')
module.exports = { netMap, helloWorld }
export { netMap, helloWorld }
and now you have a third file for which you're going to import all of hello world...
// otherModule.js
var helloWorld = require('./helloworld')
// import * as helloWorld from 'helloworld'
const x = new helloWorld.netMap(2,3)
console.log(x.a, x.b)

Exported Function isn't a Function?

Not sure why it's not viewing this as a function:
impl.js
export default function(callback){
return callback();
};
test.js
import {myModule} from '../../src/impl.js'
import {expect} from 'chai';
const module = myModule;
describe('', () => {
it('should callback when resolve is invoked', () => {
module(resolve => {
resolve('test');
}).then(value => {
expect(value).to.equal('test');
});
});
});
Error: TypeError: module is not a function
module isn't a function because where it receives its value, myModule, also isn't a function.
And, that is because you aren't using quite the correct syntax to import the export default. For that, you'll want to remove the braces around myModule:
import myModule from '../../src/impl.js'
From MDN:
Syntax
import *defaultMember* from *"module-name"*;
With the braces, the import will match a particular export by its name.
import { myModule } from '...';
Corresponds to either:
export let myModule = ...;
export function myModule() { ... };
And, impl.js doesn't export anything actually named myModule.
You don't have an export with name myModule. You only have a default export.
Either use a named export
export function myModule() { ... }
or import the the module properly
import myModule from '...';
See the export documentation on MDN for more info.

Why es6 react component works only with "export default"?

This component does work:
export class Template extends React.Component {
render() {
return (
<div> component </div>
);
}
};
export default Template;
If i remove last row, it doesn't work.
Uncaught TypeError: Cannot read property 'toUpperCase' of undefined
I guess, I don't understand something in es6 syntax. Isn't it have to export without sign "default"?
Exporting without default means it's a "named export". You can have multiple named exports in a single file. So if you do this,
class Template {}
class AnotherTemplate {}
export { Template, AnotherTemplate }
then you have to import these exports using their exact names. So to use these components in another file you'd have to do,
import {Template, AnotherTemplate} from './components/templates'
Alternatively if you export as the default export like this,
export default class Template {}
Then in another file you import the default export without using the {}, like this,
import Template from './components/templates'
There can only be one default export per file. In React it's a convention to export one component from a file, and to export it is as the default export.
You're free to rename the default export as you import it,
import TheTemplate from './components/templates'
And you can import default and named exports at the same time,
import Template,{AnotherTemplate} from './components/templates'
Add { } while importing and exporting:
export { ... }; |
import { ... } from './Template';
export → import { ... } from './Template'
export default → import ... from './Template'
Here is a working example:
// ExportExample.js
import React from "react";
function DefaultExport() {
return "This is the default export";
}
function Export1() {
return "Export without default 1";
}
function Export2() {
return "Export without default 2";
}
export default DefaultExport;
export { Export1, Export2 };
// App.js
import React from "react";
import DefaultExport, { Export1, Export2 } from "./ExportExample";
export default function App() {
return (
<>
<strong>
<DefaultExport />
</strong>
<br />
<Export1 />
<br />
<Export2 />
</>
);
}
⚡️Working sandbox to play around: https://codesandbox.io/s/export-import-example-react-jl839?fontsize=14&hidenavigation=1&theme=dark
// imports
// ex. importing a single named export
import { MyComponent } from "./MyComponent";
// ex. importing multiple named exports
import { MyComponent, MyComponent2 } from "./MyComponent";
// ex. giving a named import a different name by using "as":
import { MyComponent2 as MyNewComponent } from "./MyComponent";
// exports from ./MyComponent.js file
export const MyComponent = () => {}
export const MyComponent2 = () => {}
import * as MainComponents from "./MyComponent";
// use MainComponents.MyComponent and MainComponents.MyComponent2
//here
EXPORTING OBJECT:
class EmployeeService { }
export default new EmployeeService()
import EmployeeService from "../services/EmployeeService"; // default import
EXPORTING ARRAY
export const arrExport = [
['first', 'First'],
['second', 'Second'],
['third', 'Third'],
]
import {arrExport} from './Message' //named import
// if not react and javascript app then mention .js extension in the import statement.
You can export only one default component and in import can change the name without aliasing it(using as).

Categories

Resources