import scoped package from local in nodejs - javascript

Currently we have multiple node package published in this format
#company/module1
#company/module2
I would like to be able to load these module from local without installing it so we can modify the code directly.
So I make the link in the folder tree like this
- company/
-- module1 -> ../../module1
-- module2 -> ../../module2
Now I want when I import from the scoped name, it will load from local files instead
import module1 from '#company/module1'
Load from my other folder instead of looking from node_modules instalations.
Can anyone help me on this? Thank you very much.

You can't import the modules, libraries, or a single file in the node.js with the common import statement import Example from "package".
So, try to use the const Example = require('package') instead.
const module1 = require("path/to/the/module1");
const module2 = require("path/to/the/module2");

Related

Do I have to place any scripts/modules I create and want to import within the node_modules folder?

I am creating a VSCode extension, and following the getting started guide (https://code.visualstudio.com/api/get-started/your-first-extension) have used yeoman scaffold to get started. I created a new file, newModule.js in the same directory and want to import it as a module for use in the main extension.js script. I then do:
const newModule = require('./newModule.js');
This throws an error:
cannot find module 'newModule' require stack: -
This problem disappears if I copy my file to the node_modules folder created by default. I would like to know what is going on here, and what the best way of handling imports is when working with javascript/Node.js/vs-extensions.
I also notice that node_modules folder is not pushed to github by default, why?
The node_modules folder is for storing all the code from the libraries and packages you are using. It is excluded from git because it is a waste of space and a distraction to store them all in your versioning-control, as you can just re-download them anytime.
Just put your module in the same /src directory, and use the import syntax to import it, instead of require.
import newModule from './newModule';
For example, see how it is done in this sample code.
Please instead
const newModule = require('./newModule.js');
Try this
import newModule from './newModule');
// ^^ Do not use file extension
Also make sure that the file you are calling is in the same directory

Import JSON file in NodeJs using es6

Hi i'm currently learning nodejs and I try to import a json file like this :
'use strict'
import data from 'users.json'
console.log(data)
Each time I get this error "Cannot find package 'users.json'"
But if I read the file with fs it worked so can you explain me how to do please
try :
import data from './users'
which is the es6 method of doing things or if you want an older syntax method you can try
const data = require('./users')
Okay so the explanation just is this, those fullstops and forward slash are used to indicate relative paths to the file the import is being called from, which means somethings you'd see something like for example ../file/help. The ./ means go up one directory ../ means go up two directories and so on. The name after the slash just tells your program the folder to go in to look for the file to import from so ./folder means go up one directory and enter into the folder directory and so on.
Almost forgot to mention, you should not import from a json file or a text file or any other file that does not have a .js extention(of which you do not actually have to specify) unless absolutely neccessary. To deal with files in node you have to use the fs library.
const fs =require('fs')
....
fs.readFile('./users.json','utf-8',(err,jsonString)=>{
const data = JSON.parse(jsonString);
//whatever other code you may fanacy
}
take a look at the fs module for a list of awesome features you can use to play with files
While the selected answer is correct, here's an explanation that I hope might add some clarity:
import MyModule from 'some-module'
is ES6 import syntax, as opposed to the older CommonJS syntax, which uses require.
CommonJS's require can be used to import files generally; ES6's import statement is more specific, and is generally used for importing js files which meet the criteria for being a module (having an export statement), or specific assets such as CSS sheets. Unlike require, it won't generally work for reading in files that are not modules.
You can't mix CommonJS require and ES6 import in the same file (at least not easily), so if you're using ES6 import and wish to read a file, do so with fs.readFileSync or a similar method. If the file is a json string, you'll need to parse it with JSON.parse().
If you want to use ES6 (NOT CommonJS) module system but want to use the Node.js version which is less than V18 (supports direct json import) then use the below approach.
import { createRequire } from "module";
const require = createRequire(import.meta.url); // construct the require method
const data = require("users.json"); // Now you can use require method in ES6
console.log(data)

NPM dependency that imports/requires from the app's root

Let's say I create an app called App. It installs an npm dependency called package.
Now let's say package requires that App has the following file structure:
App/
node_modules/
package/
index.js
package.json
folder/
file.js
index.js
package.json
Within App/node_modules/package/index.js, it needs to import/require the file located at App/folder/file.js.
For example:
import File from "../../folder/file";
Is this the best way to do this? Is there any way I can reference the App's root in the import instead of needing to use ../../?
No. This is not the best way to do it. Modules should not require from their users.
Use dependency injection instead - let your user pass you the objects you require:
package/index.js
let File = null;
function init (fileModule) {
File = fileModule;
}
export init;
// ...
This way you can pass the File object from your main app:
App/index.js
import { init } from 'package';
import File from './folder/file';
init(File);
How you design the API to pass your "middleware" is up to you. The above is just a suggestion. You can pass it as an argument to a constructor for example:
const package = new Package(File);
This is in fact how frameworks like Express works. It allows Express to be extended without it knowing the structure of your code:
app.use(someMiddleware); // Express never "requires" your middleware
// instead it allows you to pass middleware to itself

How to reference a directory in javascript

I am trying to access a specific directory in javascript. I tried to have access to it using require keyword as shown below
const path = require('../../var/opt/personal/guest/op/op_12201/data/persGuesOapDataFolder00/');
but when i run the code i get the following error:
Error: Cannot find module '../../var/opt/personal/guest/op/op_12201/data/persGuesOapDataFolder00/'
please let me know how import or to use a directory in javascript
You can't possibly just import a directory unless there is index.js file within it. And in that index.js file, it should at least contain:
index.js:
import Foo from './Foo.js'
import Bar from './Bar.js'
export {
Foo,
Bar
}
And then you can finally import it:
import {Foo, Bar} from '../../components';
When you point to a directory without specifying the file, the index.js file is imported. I do not think it's possible to import an entire directory. If you want to import all the functions of a directory, you can create an index.js and explicitly export them.
See: node.js require all files in a folder?
you can do this in two different way
consider the following folder structure
-- app/
|- asset/
|- user.js
|- main.js
here main.js you can import the user.js in this way import user from '../asset/user'
other way is installing dotenv using npm i dotenv --save and following way
require('dotenv').config();
import user from './asset/user

ES6 import with dynamic file name

Is it possible to have a variable file name in the import syntax.
for example:
import * as myModule from "my-module";
to be something like this:
var module="my-module";
import * as myModule from module;
Or there is other approach for this? If not can you specify a base(root) dir from where to load the modules?
Thanks
For the baseroot I am just using a simple workaround with a symlink:
Link your src/ to the node_module/src
And use it:
import A from 'src/some/where/A
There are also other possible ways of doing it, but I am ok, with it, its really simple and it works ;)
Check out this How to make the require in node.js to be always relative to the root folder of the project?

Categories

Resources