webpack require expression missing modules - node.js

From webpack documentation, when a require expression is not known at compile time, it should generate a context module and include all the modules that could match the expression.
const handlers = {};
for (const name of Object.keys(SomeObject)) {
try {
handlers[name] = require(`./${name}.js`);
} catch {} // eslint-disable-line no-empty
}
module.exports = handlers;
however, what I get is `
const handlers = {};
for (const name of Object.keys(SomeObject)) {
try {
handlers[name] = require(`./${name}.js`);
} catch {} // eslint-disable-line no-empty
}
module.exports = handlers;
however, what I actually get is this error Cannot find module ./\u001a.js
but if I turn it into a dynamic import expression then it works
const handlers = {};
for (const name of Object.keys(SomeObject)) {
try {
import(`./${name}.js`).then(m => { handler[name] = m; });
} catch {} // eslint-disable-line no-empty
}
module.exports = handlers;
But I would prefer not to do that since the offending code is from some node package

Related

Can't acces method class, from another class (and module) in NodeJS

the title problem ! I don't know why I can't use a method from another class in NodeJS. This is my first time using classes in Node.
Let see some code:
'use strict'
api_client.js:
class ApiClient {
constructor(userQuery) {
this.userQuery = userQuery;
}
getResponse() {
try {
const response = {"my query": this.userQuery}"this is an example to simplify";
} catch(error) {
throw new Error(error.message);
}
}
}
module.exports = ApiClient;
api_service.js:
'use strict';
const apiClient = require('../clients/api_client');
class ApiService {
static async getResponse(userQuery) {
try {
const instance = await new ApiClient(userQuery);
const response = instance.getResponse(); //I think here is the problem. WebStorme tell me that I can't acces to getResponse method.
const responseJson = response.json();
return responseJson;
} catch (error) {
throw new Error(error.message);
}
}
So I can't use the "getResponse" method from ApiClient class in ApiService. Something wrong !?
thanks!

how to refer to a function when unit testing with NodeJS / Mocha

I'm making my first test with Mocha.
Dummy test is passing, but when I want to refer to my actual function that is in another file, it won't find it:
ReferenceError: main is not defined
I have a single index.js with :
async function main() {
function comparer(otherArray) {
return function (current) {
return otherArray.filter(function (other) {
return other.prm === current.prm && other.conso_prod === current.conso_prod
}).length === 0;
}
}
}
module.exports = main();
and in my test.js file, I do:
const {expect} = require('chai');
describe('Sum numbers', () => {
it('Compare 2 existing array', () => {
const meters = []
const perimeter = []
const onlyInMeters = meters.filter(main.comparer(perimeter));
expect(onlyInMeters).to.equal([]);
});
});
But when I refer to main.comparer, it can't find it:
ReferenceError: main is not defined
What am I forgetting? Sorry, I'm a NodeJS Noob!
It seems like you did not import the index.js file in test.js file. You are returning noting from main function as well.
Also, why are you exporting it like module.exports = main(); Instead you can do this:
// index.js
module.exports = {
comparer: (otherArray) => { ... }
}
// test.js
cosnt main = require('PATH_OF_index.js');
main.comparer();

why module.export { ...require('module') } work but not module.export { require('module') }

justExport.js
const first = () => {
console.log('frist from justExport')
}
const second = () => {
console.log('second fromt justExport')
}
module.exports = {
first,
second,
}
tmp.js
module.exports = {
...require('./justExport') // work
require('./justExport') // SyntaxError: Unexpected string
}
main.js
const justExport = require('./justExport.js')
const tmp = require('./tmp.js')
console.log('Hello World!')
I have voluntarily create a fake example with the less possible code.
{ ...require('./justExport') } is object literal spread. While { require('./justExport') } is incorrect object literal syntax because it doesn't contain a key.
Unless the intention is to create shallow copy of justExport module, object literal isn't needed. It can be:
module.exports = require('./justExport');
To further clarify the answer from #estus, note that the following works due to ES6 shorthand property names:
const justExport = require('./justExport');
module.exports = {
...justExport, // works
justExport // works because key is implicitly defined by variable name
}

Typescript: classes and Interfaces in definition file getting required in compiled .js

I have a Typescript project with two important files:
app.ts
models.d.ts
The first few lines of app.ts look like this:
///<reference path="models.d.ts"/>
'use strict';
import * as fs from 'async-file';
import { MyClass } from './models';
The first few lines of the compiled app.js are:
///<reference path="models.d.ts"/>
'use strict';
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const fs = require("async-file");
const models_1 = require("./models"); //// ERROR THROWN HERE!!!!!!!!
However, no models.js is generated because it's just a .d.ts declaration file. So when I run this, and require is called to get ./models, I get the following exception:
Cannot find module './models'
This is Visual Studio Professional 2017 and I don't have a tsconfig.json file. However, my project compilation settings look like this:
What am I doing wrong? This is killing me.
models.d.ts implies that there is a models.js that already exists in its place in your output directory.
You should probably use a .ts file if that isn't the case. In other words, rename it from models.d.ts to models.ts.

How to override a method in Node.js?

I have a module that defines functions that will be shared by other modules. Some of those functions need to be overridden. This is what I was thinking, but it doesn't work:
// shared_module.js
module.exports = {
alternativeFun() {
exports.doSomething()
sharedFun()
},
sharedFun() {
console.log('shared')
}
}
// alternative_module1.js
module.exports = {
doSomething() {
console.log('alternative 1')
}
}
// alternative_module2.js
module.exports = {
doSomething() {
console.log('alternative 2')
}
}
// main.js
const shared1 = require('./shared_module')
shared1.doSomething = require('./alternative_module1').doSomething
shared1.alternativeFun()
const shared2 = require('./shared_module')
shared2.doSomething = require('./alternative_module2').doSomething
shared2.alternativeFun()
Setting module.exports does not magically change the value of exports. You will need to also assign it to the same value (module.exports = exports = ...) if you want to use it inside your module's functions.

Resources