In NodeJS, how to use the same object in different files? - javascript

there are three files :
a.js
b.js
token.js
I need to use the same token in a.js and b.js, How do I achieve that? for example, set token in a.js and get token in b.js
I am using a singleton but it does not work :(
token.js
class Token {
private static instance: Token
private _hash = 'default-hash'
private constructor() {
}
static getInstance() {
if (!Token.instance) {
Token.instance = new Token()
}
return Token.instance
}
//setter and getter for _hash
}
export default Token

The module.exports or exports is a special object which is included in every JS file in the Node.js application by default. module is a variable that represents current module and exports is an object that will be exposed as a module. So, whatever you assign to module.exports or exports, will be exposed as a module.
Examples: Export Literals
File: message.js
module.exports = 'Hello world';
Now, import this message module and use it as shown below.
File: app.js
var msg = require('./messages.js');
console.log(msg);
Example: Export Object
message.js
exports.SimpleMessage = 'Hello world';
//or
module.exports.SimpleMessage = 'Hello world';
In the above example, we have attached a property "SimpleMessage" to the exports object. Now, import and use this module as shown below.
app.js
var msg = require('./messages.js');
console.log(msg.SimpleMessage);
Example: Export Function
You can attach an anonymous function to exports object as shown below.
log.js
module.exports = function (msg) {
console.log(msg);
};
Now, you can use the above module as below.
app.js
var msg = require('./log.js');
msg('Hello World');

Related

How to Eval with imported Module in ES6 and Webpack

I use Webpack as a package manager and ES6. Looks like an imported module is not correctly evaluated with eval.
How to eval a string using the imported Module ?
Code:
In a global scope:
<script type="text/javascript">
var tableDefinition = '{ value: "myvalue", myfunction: (v) => { return DateFormat.format(v) }}';
</script>
In my module:
import DateFormat from "~modules/DateFormat"; // a module helper written by me
class GeneriClass {
constructor() {
DateFormat.init();
let columns = eval(tableDefinition); // this code retrieves 'DateFormat' not defined
}
}
The error on eval is: "'DateFormat' not defined!"

Use rollup.js with jQuery adaptor in same file

I have the main function to export and the jQuery adaptor in the same file. And I would like to keep them this way.
Is there a way with rollup.js to create the bundle file compatible with AMD, CommonJS and Browsers?
Right now I have this test file:
//src/foo.js
export default function(){
function initialise() {
var TEST = {};
TEST.version = '1.0.0';
TEST.hello = function(){
console.log("hello man!!");
};
return TEST;
}
//jQuery adapter
(function($){
$.fn.demo = function(options) {
$.fn.demo.test = 'test';
};
})(jQuery);
return initialise;
};
And I tried using this rollup config:
// rollup.config.js
export default {
input: 'src/main.js',
output: {
file: 'dist/bundle.js',
format: 'umd',
globals: {
$: '$'
}
}
};
However I can't seem to have access to $.fn.demo:
// src/main.js
import jQuery from 'jQuery';
import pepe from './foo.js';
console.log(jQuery); //<--- undefined
console.log($); //<--- undefined
console.log("-- JS--");
console.log(pepe); //<---- working fine
console.log("-- $.fn.demo --");
console.log($.fn.demo); //<--- undefined
Note that in your main.js file pepe is a function (one which you exported from foo) and you didn't call it hence $.fn.demo is undefined. You must call pepe(); in order for you adapter to be executed.
See also how to tell Rollup that jquery is external and the jquery module ID equates to the global $ variable.

How to call global function from controller class in AngularJs component

In app.module.js file, import JS file from external lib
import 'assets/scripts/admin';
with global function:
function anonymousAdmin() {
"use strict";
implementation();
}
Now in app.component.js file have controller with function call:
export const AppComponent = {
controller: class AppComponent {
$onInit() {
/* global anonymousAdmin */
anonymousAdmin();
}
}
};
Run Webpack/Babel to save all files (ES6) into one file (ES5). Unfortunately i have error in console:
ReferenceError: anonymousAdmin is not defined
Someone knows how I can call this function in the controller?
anonymousAdmin is not global function. The file is imported as ES module, and ES modules force strict mode that prevents them from leaking variables to global scope.
It should be explicitly defined as a global:
function anonymousAdmin() {...}
window.anonymousAdmin = anonymousAdmin;
If the file belongs to third-party module that cannot be directly edited, and considering that Webpack is being used, the latter can be configured to expose a variable from file ES module export with exports loader, something like:
...
module: {
rules: [
{
test: require.resolve('assets/scripts/admin'),
use: 'exports-loader?anonymousAdmin'
}
]
},
...
And the function is being imported like:
import { anonymousAdmin } from 'assets/scripts/admin';
Try this one. You need to have alias for the script.
import * as admin from 'assets/scripts/admin';
export const AppComponent = {
controller: class AppComponent {
$onInit() {
/* global anonymousAdmin */
admin.anonymousAdmin();
}
}
};

Importing a Typescript Module that has a constructor

I want to break up my file into several modules. One module has a constructor. I am able to import my module into another file, but I don't know how call my constructor in the new file.
namespace CreditReports{
export class CreditReportVM {
//some code
constructor(targetElement: HTMLElement) {
ko.applyBindings(this, targetElement);
this.init();
}
public init = () => {
//some code
}
}
}
You just need to export the namespace too.
export namespace CreditReports {
//...
}
Then when you want to call the constructor:
import { CreditReports } from "./my-module";
//...
new CreditReports.CreditReportVM(myElement);
You should replace "./my-module" with the file name (an path too) where your typescript module is in.

prototype function missing when calling third party node package in Angular 2+

I am trying to use a third party Node module in an angular 2+ project.
installed with npm install --save ModuleName
The function in question is in a file named Foo.js and looks like this:
var foo = function(param1, param2) {
...
this.init();
}
foo.protoype = {
constructor: foo,
init: function(){
...
},
...
}
module.exports = foo;
index.js for the node module looks like:
var ModuleName = require("./src/ModuleName");
ModuleName.foo = require("./src/Foo");
module.exports = ModuleName;
I am trying to use the module in a Directive:
import { Directive, OnInit } from '#angular/core';
import { ModuleName } from "ModuleName"
#Directive({
selector: '[customDirective]'
})
export class CustomDirective implements OnInit {
constructor() {
...
}
ngOnInit() {
let poorlyNamedVariable = ModuleName.foo(param1, param2);
}
}
When foo is called it produces ERROR TypeError: this.init is not a function
console.log(this) in foo shows an instance of ModuleName which, in turn, has an instance of foo, which has a prototype where init is defined.
I suspect the problem stems from some sort of scoping issue, but am still too new to both Angular and Node to untangle the mess.
Use import * as ModuleName from "ModuleName" for CommonJS modules.

Categories