import class from external madule does not work in NodeJS - node.js

I'm pretty new to Node.js and try to learn it for my work.
I want to import a class name "IgApiClient" from a file with name "client.ts"
the file exists in "core" folder which it exists in "src" folder.
the file I try to run is under "example" folder which it and "src" are in one folder.
Here is screenshots of what I said:
first
second
I think I should use the import statement for this as below:
import { IgApiClient } from '../src';
which is for nodejs version before 13 and for ver 13 and above I should use this as below:
const { IgApiClient } = require('../src');
I'm using the second one for my purpose.
But when I run the code it get me this error:
the error
I also tried to move the "client" file to "node_modules" folder and replace "../src" with "../src/core/client", but none of them worked.
what's wrong with it?
How can I solve it?
If anyone has a better idea for this I appreciate it.

Use babel to use ES6 feature like classes in NodeJs. You check this as an example babel-node.

Related

Accessing typeDefs in the dist folder | NestJS/GraphQL

Context: I had a project at which backend was written with GraphQL/lambdas. Now I want to convert whole project to NestJS/GraphQL.
I have joined.graphql file in src/GraphQL folder and there is an import (usage) of this file in another .ts file. When I try to start the project with nest start command, none of *.graphql files are copied to dist folder. Then, that import throws an error as there is no joined.graphql file in the dist folder.
I tried to add nest-cli.json file with assets field to include ./**/*.graphql files as assets. Now the issue is indeed fixed. But...
Problem:
Another error occured as
/<MY_PROJECT>/dist/src/GraphQL/joined.graphql
type Query {
^^^^^
SyntacError: Unexpected identifier
The code was trying to import typeDefs. I think there should be something a bit tricky since I'm not starting the project with nest but trying to convert to nest. Maybe missing some steps to work correctly with graphql. I'm not sure.

How to access the base package form a node_module

I am looking to access a JSON config file that the user would place next to their package.json from a node_module package that I created. Is there a best approach to do this. I tried a relative import but that didn't really work and I am not sure how best to accomplish dynamic imports if the config file doesn't exist because I want to allow it to not exist as well.
Here is how I tried to handle dynamic imports though:
export const overrides = (function () {
try {
return require('../../../../../../overrides.json');
} catch (_err) {
return null;
}
})();
Also I tried fs but I get a browser config error I am not sure if that is something else. I should research but I didn't understand the docs around that.
using a library
This worked for me: find-package-json
Basically on any js file who needs the base, home or workspace path, do this:
var finder = require('find-package-json');
var path = require('path');
var f = finder(__dirname);
var rootDirectory = path.dirname(f.next().filename);
rootDirectory will be the location of the folder in which the main package.json exist.
If you want to optimize, get the appRootPath variable at the start of your app and store/propagate the variable to the hole nodejs system.
no libraries
Without any library, this worked for me:
console.log("root directory: "+require('path').resolve('./'));
This will get you the root directory of your nodejs app no matter if you are using npm run start or node foo/bar/index.js
More ways to get the root directory here:
Determine project root from a running node.js application
usage
If you achieve to obtain the root directory of your nodejs app and your file is at the package.json level, use this variable like this to locate any file at root level:
rootDirectory+"/overrides.json"

Node.js 14 ES module import from another folder

This is a FYI and a question.
I am using Node.js 14.17.3 (LTS) and wanted to take advantage of using import ES syntax to use some files in another project (which need to remain where they are).
So, I made a simple node.js app to test the import. I added "type": "module" to the package.json file in the test app folder.
The (cut down test) file mixin-modules-definitions.js to import is:
const classModuleDefs = {
name: 'mydef'
}
export default classModuleDefs
Now, if I have that file in the same folder as the package.json file of my test app, this works fine:
import classModuleDefs from './mixin-modules-definitions.js'
console.log('classModuleDefs=', classModuleDefs)
But if I try to import from where the file actually lives like the following, I get the dreaded SyntaxError: Unexpected token 'export' error.
import classModuleDefs from '../src/services/mixin-modules-definitions.js'
And, if I then add "type": "module" to the nearest package.json file relevant to that path, the error goes away and the file is imported correctly.
As it turns out, the app I am importing from is ok with adding "type": "module" to its package.json file but I could imagine a scenario where it might not be ok.
Is it possible to import a file and have node resolve to use the package.json in my test node app without needing to also change the package.json in the "source" app.
Thanks,
Murray

Symlink node_modules for files outside src

In my project I use a JSON file as a database (which is currently stored in local on my computer). It is modified by Node.js and some pieces of information are rendered with React in an import : import Data from 'myPath/appData.json';
I cannot have my database in the src folder because the build is static, and my databse must be dynamic.
I get this error :
Failed to compile.
./src/components/Ligne1.jsx
Module not found: You attempted to import myPath/appData.json which falls outside of the project src/ directory. Relative imports outside of src/ are not supported. You can either move it inside src/, or add a symlink to it from project's node_modules/.
I am now asking your help on how to add the symlink. I created the folder "appData" in node_modules with :
const fs=require('fs');
fs.symlink('.src/','.node_modules/app/',e=>{});
import Data from 'myPath/appData.json';
And using it in my component like :
import Data from 'appData';
but I also get the error :
Failed to compile.
export 'default' (imported as 'Data') was not found in 'appData'
I'm looking for a solution to ignore the restriction of the import outside src folder (symlink or something else : I already tried to change the configs of webpack but it didn't change anything) or another solution to get the information from my JSON file (which is currently stored in local on my computer).
Thank you for your time.
This restriction makes sure all files or modules (exports) are inside src/ directory, the implementation is in ./node_modules/react-dev-utils/ModuleScopePlugin.js, in following lines of code.
// Resolve the issuer from our appSrc and make sure it's one of our files
// Maybe an indexOf === 0 would be better?
const relative = path.relative(appSrc, request.context.issuer);
// If it's not in src/ or a subdirectory, not our request!
if (relative.startsWith('../') || relative.startsWith('..\\')) {
return callback();
}
You can remove this restriction by
either changing this piece of code (not recommended)
or do eject then remove ModuleScopePlugin.js from the directory.
or comment/remove const ModuleScopePlugin = require('react-dev-utils/ModuleScopePlugin'); from ./node_modules/react-scripts/config/webpack.config.dev.js
PS: beware of the consequences of eject.

Module not found error when trying to use a module as a local module

I am trying to understand as how to make a local module. At the root of node application, I have a directory named lib. Inside the lib directory I have a .js file which looks like:
var Test = function() {
return {
say : function() {
console.log('Good morning!');
}
}
}();
module.exports = Test;
I have modified my package.json with an entry of the path to the local module:
"dependencies": {
"chat-service": "^0.13.1",
"greet-module": "file:lib/Test"
}
Now, if I try to run a test script like:
var greet = require('greet-module');
console.log(greet.say());
it throws an error saying:
Error: Cannot find module 'greet-module'
What mistake am I making here?
modules.export is incorrect. It should be module.exports with an s.
Also, make sure after you add the dependency to do an npm install. This will copy the file over to your node_modules and make it available to the require function.
See here for a good reference.
Update:
After going through some examples to figure this out I noticed, most projects have the structure I laid out below. You should probably format your local modules to be their own standalone packages. With their own folders and package.json files specifying their dependencies and name. Then you can include it with npm install -S lib/test.
It worked for me once I did it, and it'll be a good structure moving forward. Cheers.
See here for the code.

Resources