ES6 how to export all item from one file - javascript

I want to export all methods of a file from another file.
currently I am doing this, and it works. How can I merge below two into 1 export expression
import * as db from './web/query';
export default db;
I tried below written 1 line exports but all failed
export * from './web/query'; //==error
export * as default from './web/query'; //==error
export * as {default} from './web/query'; //==error
export from from './web/query'; //== error
export default from './web/query'; //== error
Error means
import db from '../db/index';
db is undefined here. However the the first methods works
Inside of file './web/query' looks like
export function foo(){}
export function baar(){}

You cannot in ES2016. To create a module namespace object, you need to give it an identifier (like db) in your current module scope, and then re-export that. There's no way around it.
There is however a stage 1 proposal to add the export * as default from … syntax you were trying.

How can I merge below two into 1 export expression
You cannot.
ES2015 (and ES2016) does not provide a syntax that would allow you to import all the named exports from a file and export the object (with those as its properties) as default in a single statement.

You can export the named exports of another file with export * from '<FILE>';.
// a.js
export const one = '1';
export const two = '2';
// b.js
export * from './a.js';
// c.js
import { one, two } from './b.js';

you can do something like this:
a.js:
const fakeName = "Blabla";
const fakeAge = 33;
module.exports = {fakeName, fakeAge}
b.js:
const name = "Someone";
let age = 22;
module.exports = { name, age}
c.mjs:
export * from './a.js';
export * from './b.js';
index.mjs:
import * as AllClass from './c.mjs'
export default AllClass
use it in e.g server.mjs:
import AllClass from './index.mjs'
console.log("fakeName:", AllClass.fakeName);
console.log("NAME:",AllClass.name);
It's just hard not to get confused with ESModule imports/exports and CommonJS imports and exports...

Related

what's the difference between import "name" from "module" and import * as "name" from "module"?

The code on my app is like this.
import { HttpExceptionFilter } from './common/exceptions/http-exception.filter';
import { NestFactory } from '#nestjs/core';
import { AppModule } from './app.module';
import { ValidationPipe } from '#nestjs/common';
import { DocumentBuilder, OpenAPIObject, SwaggerModule } from '#nestjs/swagger';
//1.
import * as expressBasicAuth from 'express-basic-auth';
//2.
//import expressBasicAuth from 'express-basic-auth'; => promise unhandled error
async function bootstrap() {
const app = await NestFactory.create(AppModule);
app.useGlobalPipes(new ValidationPipe());
app.useGlobalFilters(new HttpExceptionFilter());
app.use(
['/docs', '/docs-json'],
expressBasicAuth({
challenge: true,
users: {
[process.env.SWAGGER_USER]: process.env.SWAGGER_PASSWORD,
},
}),
);
};
I want to know the difference between 1 and 2.
Because When I run my app using 2(9 lines), there was promise unhandled error.
I want to know how those two ways work. I referred to the official document of mozilla, but I couldn't understand it well.
I'd appreciate it if you could answer me.
First let's just understand how imports works
so consider i have a file with the following exports
// file name -> modules
export const add = (x, y) => x + y;
export const subtract = (x, y) => x - y;
export default (x, y) => x * y;
now i can import all these functions on another file like this
import defaultFunction, { add, subtract } from './modules.js';
console.log(add(1, 2)) // 3
console.log(subtract(2, 1)) // 1
console.log(defaultFunction(2, 2)) // 2 * 2 = 4
or i can use import * as <name> from <file/package> to import all the exports inside a file.
like this
import * as myModules from './modules.js';
// NOTE: this will only give you add and subtract functions but not the default one
// now to actually access the default function you have to use
// import * as <name> from <file/package>
// <name>.default to access the default export
// or simply
// import default, { } from <file/package>
console.log(myModules.add(1, 2)) // 3
console.log(myModules.subtract(2, 1)) // 1
console.log(myModules.default(2, 2)) // 2 * 2 = 4
// or i can destructure the "myModules" import
const { add, subtract } = myModules;
Conclusion
I think the problem is that the library that you're using is not providing a default export to actually use import expressBasicAuth from 'express-basic-auth'; or it might be exporting different functions for named exports and default exports
As per your code:
import * as expressBasicAuth from ...
Imports all export const variable1...; export const variable2...; items as a single item.
import expressBasicAuth from ...
Imports a single export default item if there was one defined inside the library.
Depending on the library implementation, there might be totally different functions exported in those two ways.
Most of the time, the module exports multiple things
There are two great ways to import from another module when the module exports an object with properties. This is the common case.
Import the whole module, giving it a name:
import * as child_process from "child_process";
// then later...
child_process.spawn(...);
or pick the names you want to import:
import { spawn } from "child_process";
// then later
spawn(...);
sometimes the module exports just one thing. typescript has the concept of export default
If a module declares a default export, then you must bring it in like this:
import thing from "thing";
Now you have a function or a class (whatever its default export is) in the thing.
More commonly in JavaScript (CommonJS?) modules, a module author will override module.exports to a function or class instead of adding properties to the exports object like a ES-module would.
so in common js we have
const expressBasicAuth = require(express-basic-auth);
and in typescript :
import * as expressBasicAuth from 'express-basic-auth';

TypeError: Cannot read property 'fraction' of undefined - Cypress/Javascript

I am doing a test where I grab an odds value and store it as a fraction. Then I want to compare the value to a particular format depending on the option selected from the drop down.
I am trying to use these to set up the fraction and determine the odds format:
https://mathjs.org/docs/datatypes/fractions.html
How do I resolve that type error above.
Screenshot:
The mathjs has no default export, so you import everything (*) and then name it in your import
import * as math from 'mathjs'
This is the main entry point for the mathjs package.
// configuration
export { config } from './configReadonly.js'
// functions and constants
export * from './pureFunctionsAny.generated.js'
export * from './impureFunctionsAny.generated.js'
export * from './typeChecks.js'
// error classes
export { IndexError } from '../error/IndexError.js'
export { DimensionError } from '../error/DimensionError.js'
export { ArgumentsError } from '../error/ArgumentsError.js'
// dependency groups
export * from './dependenciesAny.generated.js'
// factory functions
export * from '../factoriesAny.js'
// core
export { create } from '../core/create.js'
export { factory } from '../utils/factory.js'
If it had a default export, there would be
export default {
function1,
function2,
function3,
...
}
and then you can import it without using * as math.
If you want to use just fraction you can use:
const { fraction } = require("mathjs");
//In your test
fraction(oddsValue);
If you want to use others as well, you can do:
import { create, all } from "mathjs"
const math = create(all, {})
//In your test
math.fraction(oddsValue)

Purpose of "default" keyword in "export default object" in react, cant we avoid writting "default" keyword? [duplicate]

I am trying to determine if there are any big differences between these two, other than being able to import with export default by just doing:
import myItem from 'myItem';
And using export const I can do:
import { myItem } from 'myItem';
Are there any differences and/or use cases other than this?
It's a named export vs a default export. export const is a named export that exports a const declaration or declarations.
To emphasize: what matters here is the export keyword as const is used to declare a const declaration or declarations. export may also be applied to other declarations such as class or function declarations.
Default Export (export default)
You can have one default export per file. When you import you have to specify a name and import like so:
import MyDefaultExport from "./MyFileWithADefaultExport";
You can give this any name you like.
Named Export (export)
With named exports, you can have multiple named exports per file. Then import the specific exports you want surrounded in braces:
// ex. importing multiple exports:
import { MyClass, MyOtherClass } from "./MyClass";
// ex. giving a named import a different name by using "as":
import { MyClass2 as MyClass2Alias } from "./MyClass2";
// use MyClass, MyOtherClass, and MyClass2Alias here
Or it's possible to use a default along with named imports in the same statement:
import MyDefaultExport, { MyClass, MyOtherClass} from "./MyClass";
Namespace Import
It's also possible to import everything from the file on an object:
import * as MyClasses from "./MyClass";
// use MyClasses.MyClass, MyClasses.MyOtherClass and MyClasses.default here
Notes
The syntax favours default exports as slightly more concise because their use case is more common (See the discussion here).
A default export is actually a named export with the name default so you are able to import it with a named import:
import { default as MyDefaultExport } from "./MyFileWithADefaultExport";
export default affects the syntax when importing the exported "thing", when allowing to import, whatever has been exported, by choosing the name in the import itself, no matter what was the name when it was exported, simply because it's marked as the "default".
A useful use case, which I like (and use), is allowing to export an anonymous function without explicitly having to name it, and only when that function is imported, it must be given a name:
Example:
Export 2 functions, one is default:
export function divide( x ){
return x / 2;
}
// only one 'default' function may be exported and the rest (above) must be named
export default function( x ){ // <---- declared as a default function
return x * x;
}
Import the above functions. Making up a name for the default one:
// The default function should be the first to import (and named whatever)
import square, {divide} from './module_1.js'; // I named the default "square"
console.log( square(2), divide(2) ); // 4, 1
When the {} syntax is used to import a function (or variable) it means that whatever is imported was already named when exported, so one must import it by the exact same name, or else the import wouldn't work.
Erroneous Examples:
The default function must be first to import
import {divide}, square from './module_1.js
divide_1 was not exported in module_1.js, thus nothing will be imported
import {divide_1} from './module_1.js
square was not exported in module_1.js, because {} tells the engine to explicitly search for named exports only.
import {square} from './module_1.js
More important difference is: export default exports value, while export const/export var/export let exports reference(or been called live binding). Try below code in nodejs(using version 13 or above to enable es module by default):
// a.mjs
export let x = 5;
// or
// let x = 5;
// export { x }
setInterval(() => {
x++;
}, 1000);
export default x;
// index.mjs
import y, { x } from './1.mjs';
setInterval(() => {
console.log(y, x);
}, 1000);
# install node 13 or above
node ./index.mjs
And we should get below output:
6 5
7 5
8 5
...
...
Why we need this difference
Most probably, export default is used for compatibility of commonjs module.exports.
How to achieve this with bundler(rollup, webpack)
For above code, we use rollup to bundle.
rollup ./index.mjs --dir build
And the build output:
// build/index.js
let x = 5;
// or
// let x = 5;
// export { x }
setInterval(() => {
x++;
}, 1000);
var y = x;
setInterval(() => {
console.log(y, x);
}, 1000);
Please pay attention to var y = x statement, which is the default.
webpack has similar build output. When large scale of modules are added to build, concatenateing text is not sustainable, and bundlers will use Object.defineProperty to achieve binding(or called harmony exports in webpack). Please find detail in below code:
main.js
...
/******/ // define getter function for harmony exports
/******/ __webpack_require__.d = function(exports, name, getter) {
/******/ if(!__webpack_require__.o(exports, name)) {
/******/ Object.defineProperty(exports, name, { enumerable: true, get: getter });
/******/ }
/******/ };
...
// 1.js
(window["webpackJsonp"] = window["webpackJsonp"] || []).push([[1],[
/* 0 */,
/* 1 */
/***/ (function(__webpack_module__, __webpack_exports__, __webpack_require__) {
"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, "x", function() { return x; });
let x = 5;
// or
// let x = 5;
// export { x }
setInterval(() => {
x++;
}, 1000);
/* harmony default export */ __webpack_exports__["default"] = (x);
/***/ })
]]);
Please find the difference behavior between /* harmony export (binding) */ and /* harmony default export */.
ES Module native implementation
es-modules-a-cartoon-deep-dive by Mozilla told why, what and how about es module.
Minor note: Please consider that when you import from a default export, the naming is completely independent. This actually has an impact on refactorings.
Let's say you have a class Foo like this with a corresponding import:
export default class Foo { }
// The name 'Foo' could be anything, since it's just an
// Identifier for the default export
import Foo from './Foo'
Now if you refactor your Foo class to be Bar and also rename the file, most IDEs will NOT touch your import. So you will end up with this:
export default class Bar { }
// The name 'Foo' could be anything, since it's just an
// Identifier for the default export.
import Foo from './Bar'
Especially in TypeScript, I really appreciate named exports and the more reliable refactoring. The difference is just the lack of the default keyword and the curly braces. This btw also prevents you from making a typo in your import since you have type checking now.
export class Foo { }
//'Foo' needs to be the class name. The import will be refactored
//in case of a rename!
import { Foo } from './Foo'
From the documentation:
Named exports are useful to export several values. During the import, one will be able to use the same name to refer to the corresponding value.
Concerning the default export, there is only a single default export per module. A default export can be a function, a class, an object or anything else. This value is to be considered as the "main" exported value since it will be the simplest to import.
When you put default, its called default export. You can only have one default export per file and you can import it in another file with any name you want. When you don't put default, its called named export, you have to import it in another file using the same name with curly braces inside it.

"Uncaught TypeError: Object(...) is not a function" when importing a function through a barrel

I have a function in a file called merge, which contains inside it
export default (prev, next) => Object.assign({}, prev, next)
I also have a barrel which imports and exports this function like
import fetchToNode from './fetchToNode'
import mergeObjects from './mergeObjects'
export {
fetchToNode,
mergeObjects
}
If I import the function from it's origin (import merge from 'src/functions/merge') everything works fine.
If I try to import this function from the barrel however (import {merge} from 'src/functions') then I get the error
redux.js:449 Uncaught TypeError: Object(...) is not a function
You are not exporting from the barrel correctly. Try something like this:
src/functions/index.js:
export { default as mergeObjects } from './mergeObjects';
export { default as fetchToNode } from './fetchToNode';
and then
import { mergeObjects, fetchToNode } from 'src/functions';
The way you've exported it is for the following usage:
import functions from 'src/functions';
console.log(functions.merge) // merge function
You can check out this useful link about barrel exports
See how it curates these examples for the barrel?
export * from './mergeObjects'; // re-export all of its exports
export * from './fetchToNode'; // re-export all of its exports
In our case, we don't need to re-export all of the exports (but the snippet above also works), but only the default of it, since your function is written as such:
export default (prev, next) => Object.assign({}, prev, next)
Thus export { default as merge } from './merge' default means on export default () ... from the function above in merge.js
Update your barrel file to and it should fix it:
export * from './fetchToNode'
export * from './mergeObjects'

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