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';
Related
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,
}
I have a JS file containing this code:
module.exports = function loadMyFun() {
function activateSite($currentItem) {
...
}
...
}
And I want to import it into a JSX file, I tried to do it like this but I doesn't work:
import MyNav from './MyNav.js';
const top = MyNav.activateSite();
componentDidMount () {
var self = this;
MyNav.activateSite($(self));
}
...
I get this error:
Uncaught TypeError: _MyNav.default.activateSite is not a function
Any idea how to solve this?
activateSite is a variable that is locally scoped to the loadMyFun function.
It is not available outside the scope of loadMyFun.
It is not a property of the loadMyFun function object.
You cannot access it without rewriting the module.
e.g.
module.exports = function loadMyFun() {
};
module.exports.activeSite = function activateSite($currentItem) {
};
If the code you provided is actually the module you are trying to load, then there are a few problems with that module.
You are exporting a constructor loadMyFun, which you are not calling/instantiating after importing it.
If you would instantiate your constructor like this const myNav = new MyNav() you would have a instance of your exported constructor.
To make your activateSite function work, you would have to assign it to the instance itself and move it out of the local scope of loadMyFunc by assigning it like this: this.activateSite = function(){...}
If you dont need any information wrapped around your activateSite function I would recommend you export an object with your functions instead of the loadMyFun approach.
//myModule.js
module.exports = {
activateSite: function(){ ... }
}
//otherFile.js
import { activateSite } from './myModule.js' // With destructuring
activateSite()
import myModule from './myModule.js' // Without destructuring
myModule.activateSite()
I am using Babel to compile some ES6 JavaScript down to ES5. I am having some trouble with my code because my modules are being evaluated in an undefined order.
Let's say I have a modules:
// a.js
class A {
constructor() {
this.prop = window.randomProperty;
console.log("Prop " + this.prop);
}
}
const a = new A();
export default a;
This module relies on window.randomProperty to be set before it can instantiate itself.
Now I have a main file:
// main.js
import "babel-polyfill"; // Not sure if this is relevant
window.randomProperty = function() { return "hi"; };
console.log("randomProperty set");
import A from "a";
The console output of this is:
Prop undefined
randomProperty set
How can I have the code execute in the correct order?
import statements are hoisted, so imports are loaded before your code is executed. To execute it in order you want, you should use other module loader such as using require.
const A = require("a");
Imports are loaded (and executed, unless cyclic) before the module is executed statically. In your case, a.js will be loaded before main.js is executed.
If you have dependencies, you should declare them explicitly:
// random_prop.js
window.randomProperty = function() { return "hi"; };
console.log("randomProperty set");
// a.js
import "random_prop";
const a = {
prop: window.randomProperty;
}
console.log("Prop " + a.prop);
export {a as default}
// main.js
import "babel-polyfill"; // Not sure if this is relevant
import a from "a";
console.log(a.prop);
Of course, you could also import the random_prop.js in main.js before a.js, and it would work in this simple setting, but I would not recommend relying on side effects like that.
Your problem lies in where you instantiate A, try doing it in main.js. Check this out:
// a.js
class A {
constructor() {
this.prop = window.randomProperty;
console.log("Prop " + this.prop);
}
}
// do not instantiate here
// const a = new A();
export default a;
Just make sure you create the object here:
// main.js
import A from "a";
window.randomProperty = function() { return "hi"; };
console.log("randomProperty set");
const a = new A();
The reason is, when you import a module, it will invoke any methods that are not tied to a function or class definition.
Hope this helps!
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};
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();