whats the point of bracket after word import - javascript

import { something } from 'something.js'
Whats the point of brackets after word import? i know that in ES6 brackets can work in two ways, either as closure or as object which will automatically set the key and value, but how it works in import case

That's how you do a named import. Something.js will have something like this in it:
export const something = 'hello'
if instead it had a default export:
const something = 'hello';
export default something;
Then you would import it using:
import something from 'something.js'
See also Destructuring, which uses similar (but not identical) syntax

reference: https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Statements/export
// using.js
import { something1, something2 } from './somethings'
// somethings.js
const something1 = "1";
const something2 = "2";
export {
something1,
something2,
}

Related

How to return non static variable from static method ES6 Class

I have following code:
export class Utils{
constructor() {
this.dateFormat = "MM-DD-YY";
}
static getFormat() {
return this.dateFormat;
}
}
when I am trying to import this class to other file and try to call the static method gteFormat it return undefined.
Here is how I am doing it:
import * as Utils from "./commons/Utils.js";
class ABC {
init(){
console.log(Utils.Utils.getFormat());// gives undefined
}
}
How can I make this static method return the dateFormat property?
If you are conceptually working with a bunch of functions, you can consider relying on the module scope itself for privacy, rather than the class structure. Then you can export functions or values directly. Like
const dateFormat = "MM-DD-YY";
export function getFormat() {
return dateFormat;
}
with usage like
import * as Utils from "./commons/Utils.js";
console.log(Utils.getFormat())
or even
import { getFormat } from "./commons/Utils.js";
console.log(getFormat())
or if it's literally a constant you can export it directly
export const DATE_FORMAT = "MM-DD-YY";
then
import { DATE_FORMAT } from "./commons/Utils.js";
console.log(DATE_FORMAT);
Exporting a class with a bunch of static methods is a very Java-y way to write it, and the class itself adds nothing.
Constructors are for instances
Think about it: a constructor is called when an instance is created, setting static defaults is probably better done elsewhere, for example when declaring the static variable
class Utils {
static dateFormat = "MM-DD-YY";
static getFormat() {
return this.dateFormat;
}
}
console.log(Utils.getFormat())
If, for some reason, you have to set this in a constructor anyways, the correct syntax will be Utils.dateFormat = "...". Funny side fact is that you can use this when reading (in the return statement). However, you would still have to instanciate an instance of Utils in order for dateFormat to be sth. other than undefined:
class Utils {
static dateFormat;
constructor() {
Utils.dateFormat = "MM-DD-YY"; // use Utils.dateFormat when writing
}
static getFormat() {
return this.dateFormat; // use whatever you like when reading... :/
}
}
console.log(`Before instanciating: ${Utils.getFormat()}`);
var dummy = new Utils();
console.log(`After instanciating: ${Utils.getFormat()}`);
A sidenote on your import statement
you could avoid having to call Utils.Utils.getFormat() everytime, which looks a bit weird, by refactoring your import-statement like so:
// import * as Utils from "./commons/Utils.js";
import { Utils } from "./commons/Utils.js";
class ABC {
init(){
//console.log(Utils.Utils.getFormat());
console.log(Utils.getFormat());
}
}

es6 equivalent for module.exports

What's the ES6 equivalent for module.exports
I want to get the value of foo from an import statement
module.exports = {
foo: function (a) {
}
}
Tried:
export default {
foo: function (a) {
}
}
The way first one is imported is using:
var file;
var filename = root + "/" + fileStats.name;
file = require(path.resolve(filename));
I want to use ES6 import statement. I read somewhere that this isn't supported however would like to still know if there's a work around this.
Not sure what you're trying to do because in the code you supplied you did not consume the actual foo method from the object you imported.
But if I understand correctly, you could achieve this in one of 2 ways:
export default function foo(a) { };
and consume the module with:
import foo from './<filename>.js';
Or alternatively, don't use the default export:
export function foo(a) {};
and consume with:
import { foo } from './<filename>.js';

Static class in typescript

Is there any way to create an static class in typescript, node.js
I want to create an static class to keep all constants and string in that.
what could be the best way to do that ?
Sure you can define a class with static properties:
export class Constants {
static MAX_VALUE = 99999;
static MIN_VALUE = 0;
}
Then use it when you need:
import { Constants } from '../constants';
console.log(Constants.MAX_VALUE);
You can put your variables and functions you want inside a module which means that it doesn't have to be instantiated.
module constants {
export var myValue = 'foo';
export function thisIsAStaticLikeFunction () {
console.log('function called');
}
}
.....
console.log(constants.myValue);
There really is no such thing as a true static class, but this comes pretty close to replicating it.
Now you can use Enums like that:
export enum Numbers {
Four = 4,
Five = 5,
Six = 6,
Seven = 7
}
Then use it:
import { Numbers } from './Numbers';
Numbers.FIVE

Why to you have to specify the type of the export (let, var, const...) in ES2015?

As I'm reading here, ES2015 allows you to export var, const, let, function, class and default.
export var myVar1 = ...;
export let myVar2 = ...;
export const MY_CONST = ...;
export function myFunc() {
...
}
export function* myGeneratorFunc() {
...
}
export class MyClass {
...
}
But I don't understand why. In my layman opinion, there should be named exports and default exports.
The type of what you are exporting doesn't seem to matter. I mean, when you export default, do you specify the type? No you don't, and it works. Additionally, what difference can it make to export var or let? What difference can it make to export const? When you import a module it's immutable anyway (AFAIK).
So, why do you have to specify the type of the export?
You don't have to specify the type of the export - you have to specify the type of the local binding in your module.
there should be named exports and default exports.
There are:
export {localX as exportedX};
export {localX as default};
All those examples you've given are actually shorthands, which both declare a local variable and export it under the same name:
var myVar1 = …;
let myVar2 = …;
const MY_CONST = …;
function myFunc() {
…
}
function* myGeneratorFunc() {
…
}
class MyClass {
…
}
export {
myVar,
myVar2,
MY_CONST,
myFunc,
myGeneratorFunc,
myClass
};
What difference can it make to export const? When you import a module it's immutable anyway.
That you cannot reassign it inside your module. The export doesn't export a value1, it exports a binding to your local variable. Imports actually aren't immutable, they are only non-writable.
// example.js
export var value; // this one would not work with `const`
export default function(x) {
value = x;
}
// main.js
import write, {value} from 'example';
console.log(value); // undefined
write(42);
console.log(value); // 42
1: Default exports are a bit special in that regard. The export default … declaration does indeed allow you to directly export the value of an expression (or an anonymous function/function*/class declaration), but behind the scenes it actually does create a local variable in your module with the name *default*.
Declaring variables, functions or the new const values doesn't have anything to do with exports. The behavior of a var, let or const is different within a module, so you need to indicate what it is. If you export it or not is another thing.
The values are immutable from the outside of a module, but not from the inside (from another exported function for instance).
export let mutable = 1;
export const immutable = 2;
export function change() {
mutable = 11; //works
immutable = 22; //throws, the value is const
}
you are combining variable declaration with module exports with code like
export const x = 10;
in the same way that you can't declare a variable with only
x = 10;
you can't declare a variable and then assign it to a named export with
export x = 10;
Here is what you can do:
const x = 10;
const y = (arg) => arg + 10;
export { x, y };
This is essentially just separating the logic of variable declaration and naming module exports
If your export is default, you don't have to specify name or type of what you are exporting, so you can do:
export default "whateveryoulike";
but named exports are different, you have to specify variable name so that you can import it by this name (type is not important):
const x = "whateverelse";
const y = "onemore";
export {x, y as z};

module.exports that include all functions in a single line

This is a follow-up question to In Node.js, how do I "include" functions from my other files?
I would like to include an external js file that contains common functions for a node.js app.
From one of the answers in In Node.js, how do I "include" functions from my other files?, this can be done by
// tools.js
// ========
module.exports = {
foo: function () {
// whatever
},
bar: function () {
// whatever
}
};
var zemba = function () {
}
It is inconvenient to export each and every function. Is it possible to have a one-liner that exports all functions? Something that looks like this;
module.exports = 'all functions';
It is so much more convenient this way. It is also less buggy in case one forgets to export certain functions later.
If not a one-liner, are there simpler alternatives that make coding more convenient? I just want to include an external js file made up of common functions conveniently. Something like include <stdio.h> in C/C++.
You can write all your function declarations first and then export them in an object:
function bar() {
//bar
}
function foo() {
//foo
}
module.exports = {
foo, bar
};
There's no magical one-liner though, you need to explicitly export the functions you want to be public.
I have done something like the following:
var Exported = {
someFunction: function() { },
anotherFunction: function() { },
}
module.exports = Exported;
I require it in another file and I can access those functions
var Export = require('path/to/Exported');
Export.someFunction();
This is essentially just an object with functions in it, and then you export the object.
A really old question but I just had to solve the same issue myself.
the solution I used was to define a Class inside the module to contain all my functions and simply export an instance of the class.
classes.js looks like this:
class TestClass
{
Function1() {
return "Function1";
}
Function2() {
return "Function2";
}
}
module.exports = new TestClass();
app.js looks like this:
const TestClass = require("./classes");
console.log( TestClass.Function1);
just keep adding more functions to the class and they will be exported :)
It is worth noting that in ES6, you can now export functions like this:
export function foo(){}
export function bar(){}
function zemba(){}
Simply write export before the functions you want to export. More information here.
If you use ES6 you can do something like that:
function bar() {
//bar
}
function foo() {
//foo
}
export default { bar, foo };
const fs = require("fs")
var ExportAll = {
deleteFile : function deleteFile(image,folder="uploads"){
let imagePath = `public/${folder}/${image}`
if (fs.existsSync(imagePath)){
fs.unlinkSync(imagePath)
}
},
checkFile : function checkFile(image,folder="uploads"){
let imagePath = `public/${folder}/${image}`
if (fs.existsSync(imagePath)){
return true
}
else{
return false
}
},
rand : function(min=1,max=10)
{
return Math.floor((Math.random() * max) + min)
}
}
module.exports = ExportAll
Import everything from a type module file that has functions that are exported.
Found here:
https://javascript.info/import-export
myfile.js
export function myFunction()
{
// ................
}
export function myFunction2()
{
// ................
}
myfile2.js - import everything that is exported in the file
import * as myFunctions from './myfile.js';
// Usage
myFunctions.myFunction();
myFunctions.myFunction2();

Categories