How to import a static member of a class? - javascript

I am trying to import a static member of a class into a file by just using standard import syntax. To give context:
Destructuring works on the static method of a class:
class Person {
static walk() {
console.log('Walking');
}
}
let {walk} = Person;
console.log(walk); // walk function
However, I thought imports behaved like destructuring assignments. If that's true, then I would expect the following to work. But, when I attempt to import the walk method, it just comes back as undefined:
Destructuring through imports, why doesn't it work?
person.js
export default class Person {
static walk() {
console.log('Walking');
}
}
walker.js
import {walk} from './person';
console.log(walk); // undefined
Since this doesn't seem to work, how can I import a static method from a class to another module?

export default can be mixed with normal exports in ES6. For example :
// module-a.js
export default a = 1;
export const b = 2;
// module-b.js
import a, { b } from "./module-a";
a === 1;
b === 2;
This means that the import brackets are not the same as a destructor assignment.
What you want to achieve is actually not possible in the ES6 specs. Best way to do it, would be to use the destructuring after your import
import Person from "./person";
const { walk } = Person;

The syntax you are using is actually a named import, not a destructuring assignment, although they look similar. There is no destructuring import in ES6. All you can do is to add a destructuring assignment to the next line, but keep in mind that this will break when the imports are cyclic.
import Person from './person';
const { walk } = Person;
console.log(walk);

Related

Calling a function from a class to another generate an error in Next.js [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.

Use Typescript declaration types inline

After installing types for a library such as "#types/openlayers" how can I then use these for inline type definitions for things like React props:
import Map from "ol/Map";
import { Map as MapTypes } from "#types/openlayers"; // Error: Cannot import type declaration files.
export type Props = {
mapInstance: MapTypes;
}
export const OlMap: FunctionComponent<Props> = (props): JSX.Element => {
const currentMap = props.mapInstance;
...
}
Use it from the actual package that is being typed, not the #types/* module. For example, with react-router, you add #types/react-router but to pull out the RouteProps interface, you use import {RouteProps} from "react-router";.
Additionally, from your edits, it seems that you may be using the wrong #types/* package. You mention using #types/openlayers but then mention that you are using the package ol, which should probably use the #types/ol package for types.
Note declaration file consumption:
For the most part, type declaration packages should always have the
same name as the package name on npm, but prefixed with #types/
After running yarn add ol #types/ol (or npm i ol #types/ol)
This seems to be using the right types:
import MapTypes from "ol/Map"; // Note that I don't need "{}" or "as" here
// import {Map as MapTypes} from "ol"; or pull it out of the root export
export type Props = {
mapInstance: MapTypes;
}
export const OlMap: FunctionComponent<Props> = (props): JSX.Element => {
const currentMap = props.mapInstance;
...
}

How to import sub objects

Given these exports in a plugin
// Imagine these inner functions are written somewhere
export const WindowFunctions={
maximize: maximizeFunction,
minimize: minimizeFunction
}
export const FileFunctions={
open: openFileFunction,
close: closeFileFunction
}
// Pretend there is 20 other exports here
export default{
WindowFunctions,
FileFunctions,
// imagine those 20 other exports here too
}
When using require, you could access them with
const {maximize} = require('yourPlugin').WindowFunctions
How can this be achieved with import instead?
So far I have been doing this
import {WindowFunctions} from 'yourPlugin'
const maximize = WindowFunctions.maximize
Is there a nicer way to import these?
Thanks
import {WindowFunctions: {maximize}} from 'yourPlugin'
ES2015 named imports do not destructure. Use another statement for destructuring after the import.

TypeScript sub modules?

Currently I do this:
import {validators} from 'marker';
validators.isEmail('foo#bar.com');
Instead, I would like:
isEmail('foo#bar.com');
// Without cheating by just: `const isEmail = validators.isEmail`
How do I import just the isEmail symbol?
Here's a little test-case, note that my actual module has many validators and other submodules (not just validators)
marker.d.ts
declare var marker: marker.marker;
declare module marker {
export interface marker {
validators: IValidators;
}
export interface IValidators {
isEmail(input: string): boolean;
}
}
export = marker;
index.ts
import * as vs from './validators'
export const validators = vs;
validators.ts
export function isEmail(input: string): boolean { return true }
You should cheat. But you can make that cheating prettier using further destructuring (more https://basarat.gitbooks.io/typescript/content/docs/destructuring.html). Instead of
const isEmail = validators.isEmail;
You can
const {isEmail} = validators;
You could try
const { validators: { isEmail } } = require('marker');
isEmail('aaa#bbb');
Note sure where exactly you don't want to include
// Without cheating by just: `const isEmail = validators.isEmail`
Below solution is based upon assumption that you do not want isEmail to be defined in the ts file where you are using validators.isEmail.
Assuming index.ts your main file for marker package, you may expose all validator methods directly.
index.ts
import * as vs from './validators'
export const isEmail = vs.isEmail;
and use it like below,
import { isEmail } from 'marker';
isEmail('foo#bar.com');
you also have to make necessary changes in definition files.

Splitting up class definition in ES 6 / Harmony

Suppose I have a class in one big file like this:
export default class {
constructor () {}
methodA () {}
methodB () {}
methodC () {}
}
And I want to break up the class definition so that methodA, methodB, and methodC are each defined in their own separate files. Is this possible?
You should be able to, as class is supposed to just be syntax sugar for the usual prototype workflow:
import methodOne from 'methodOne'
import methodTwo from 'methodTwo'
class MyClass {
constructor() {
}
}
Object.assign(MyClass.prototype, {methodOne, methodTwo})
export default MyClass
#elclanrs gave a correct answer, but I would modify it to allow for the use of this. I also think this is more readable.
import methodOne from 'methodOne'
import methodTwo from 'methodTwo'
class MyClass {
constructor() {
this.methodOne = methodOne.bind(this)
this.methodTwo = methodTwo.bind(this)
}
}
export default MyClass
Tip: although if your class is so large that it warrants being split into multiple files, a better solution might be to split up the class into multiple classes.

Categories