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()
Related
I have two files, 'Drawer.ts' and the 'sidenav-open-close.component.ts' componenet.
I need a variable to be shared between these two, with the option to change it's value in 'Drawer.ts', and 'sidenav-open-close.component.ts' will act accordingly.
I tried using this method -
What is the best way to declare a global variable in Angular 2 / Typescript
and created a file named globals.ts with these conntent:
'use strict';
export var diffMode : boolean = false;
and imported it in both files with import * as myGlobals from './src/globals.ts';
I managed to read diffMode, but when trying to set it through 'Drawer.ts' i get the following error:
ERROR TypeError: Cannot set property diffMode of [object Object] which has
only a getter
Help will be appreciated, Thanks.
With JavaScript modules (aka "ESM" for ECMAScript Module), which TypeScript now uses, imports are a read-only view of the export, which is why you can't write to diffMode from outside the module it's defined in.
If you need to write to it from a different module, you can expose a function to set its value instead:
'use strict';
export var diffMode : boolean = false;
export function setDiffMode(flag: boolean) {
diffMode = flag;
}
...and then call that function from the other module, rather than writing to it directly.
Live Example (in JavaScript, but it doesn't matter) on plunker (Stack Snippets don't allow modules, sadly).
main.js:
const handle = setInterval(() => {
const p = document.createElement("p");
p.appendChild(
document.createTextNode(`diffMode = ${diffMode}`)
);
document.body.appendChild(p);
}, 250);
setTimeout(() => {
clearInterval(handle);
}, 1000);
export var diffMode = false;
export function setDiffMode(flag) {
diffMode = flag;
}
othermod.js:
import {diffMode, setDiffMode} from "./main.js";
setTimeout(() => {
setDiffMode(true);
}, 500);
If you run that, you'll see that the change othermod.js makes to diffMode does happen and get observed by main.js's code.
Side note: Modules are always in strict mode, so you don't need the 'use strict'; at the top.
I am trying to access the function from another file like below:
exp1.js
module.exports = function(RED) {
function expIn(config) {
//some code
}
}
I want to access "expIn()" in another file called exp2.js how can i achieve this??
please help me.
As is, you are not exporting expIn(). You are exporting the outer function in which expIn() is declared and defined. expIn() is just a local variable and cannot be accessed outside of the anonymous outer function you are actually exporting. To make it visible to other files, you either have to export it directly or define it on the exported function.
You're missing some code, but you have 3 options for accessing expIn() outside of exp1.js. First is to export it directly
exp1.js
module.exports = function expIn(config) {
// Code...
};
exp2.js
const { expIn } = require('exp1.js');
expIn({/*config*/});
Alternatively, you could add expIn() to the outer function's prototype. This is usually done when you want to export a class with several methods attached to it. You can do this one of 2 ways. First, the method most similar to what you're already doing is
exp1.js
module.exports = function ClassName(/*constructor args*/) {
this.expIn = function expIn(config) {
// Code...
};
// Other initialization...
};
Alternatively, you could define expIn() more explicitly on the prototype using this method:
exp1.js
function ClassName(/*constructor args*/) {
// Initialize class.
}
ClassName.prototype.expIn = function expIn(config) {
// Code...
};
module.exports = ClassName;
Regardless of which of the 2 methods you choose above, you would access it as
const ClassName = require('exp1.js');
let classInstance = new ClassName();
classInstance.expIn({/*config options/*});
One last method you could use is defining expIn() as a static method on the function class. This would look like:
exp1.js
function ClassName(/*constructor args*/) {
// Initialization code...
}
ClassName.expIn = function expIn(config) {
// Code...
};
module.exports = ClassName;
exp2.js
const ClassName = require('exp1.js');
ClassName.expIn(/*config options*/);
This i resolved by adding function out side the function(RED):
module.exports = function(RED) {
}
function expIn(config) {
//some code
}
And then exported as normal like :
module.exports.expIn = expIn;
then it starts working.
I am not sure whether this is a correct method or not but it serves my requirement.
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';
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();
Using requires, I’ve split larger class structures down into modules that use other modules within directory. There’s a main file that instantiates the other sub modules. This is an API class with two modules. One that deals with posting data to the endpoint, and the other that holds functions that are helpers to that post module:
define([
'./Post',
'./Helper'
], function (PostModule, HelperModule) {
'use strict';
var module = function () {
this.Post = new PostModule();
this.Helper = new HelperModule();
};
return module;
});
Now I can chain these modules like this:
var foo = new ApiModule();
foo.Post.postToAPI();
foo.Helper.matchAPIactionToEvent();
which is exactly what I want..
BUT, the problem is within the Post.js file, is that it doesn’t know anything about the Helper.js file. So I can’t take advantage of any of those methods. What I would like to do within the Post.js file is to be able to reference the other functions within the same class like so:
define([
'../environment',
'loglevel',
'../utility/Utility',
'jquery'
], function (EnvironmentModule, log, UtilityModule, $) {
'use strict';
var module = function () {
var environment,
utility,
api;
environment = new EnvironmentModule();
utility = new UtilityModule();
this.postToAPI = function (event, payload, callback) {
var apiEndpoint,
requestIdString,
eventAndAction;
apiEndpoint = environment.getEnvironmentPath().API;
requestIdString = utility.String.generateRandomString(32);
/*** THIS IS HOW I WANT TO CALL THE HELPER METHODS ***/
eventAndAction = this.Helper.matchAPIactionToEvent(event);
/*** THIS IS HOW I WANT TO CALL THE HELPER METHODS ***/
payload.event = eventAndAction.event;
payload.action = eventAndAction.action;
payload.requestID = requestIdString;
payload = $.param(payload);
$.post(apiEndpoint + '?' + payload, function (result) {
if (callback) {
callback(result);
}
});
return;
};
};
return module;
});
I figured out a working solution to the this, where I pass '../api/Helper' as one of the array values in the define statement of Post.js; but I don’t want to do that. What I want is to have Post.js be able to access any method from any other modules that are contained within the same directory. That way I don’t have to explicitly define them. It seems wrong to instantiate a new ApiModule() within Post.js. Here’s the directory structure:
Modules/api/Api.js
Modules/api/Post.js
Modules/api/Helper.js
...
I hope that makes sense. Is this possible?
Since you want any of the child modules to access any other child modules, what you could do is pass the parent module as an argument to the constructors of the child modules:
var module = function () {
this.Post = new PostModule(this);
this.Helper = new HelperModule(this);
};
Have the child modules store this information:
var module = function (parent) {
this.parent = parent;
Then use this this.parent to call the methods on other child modules:
eventAndAction = this.parent.Helper.matchAPIactionToEvent(event);
Note that if you would load '../api/Helper' with RequireJS in Post.js as you were thinking of doing, you would not be able to use the same object instance as the one defined on the parent module. You'd have to construct a new object for use in Post.js.