Ask Your Question
0

What is the method to import JavaScript files in NodeJS using project root file paths instead of relative paths?

asked 2022-02-03 11:00:00 +0000

bukephalos gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2022-03-18 00:00:00 +0000

nofretete gravatar image

To import JavaScript files in NodeJS using project root file paths instead of relative paths, you can set the NODE_PATH environment variable to the root directory of your project.

Here are the steps to follow:

  1. Open the terminal and navigate to the root directory of your project.

  2. Set the NODE_PATH environment variable to the root directory of your project by running the following command:

    export NODE_PATH=./
    

    This will set the NODE_PATH to the current directory, which is the root of your project.

  3. Create a src directory in the root of your project, and place your JavaScript files in this directory.

  4. In your code, you can import your JavaScript files using the project root file path as follows:

    const myModule = require('src/myModule.js');
    

    Note that you don't need to specify the relative path to the src directory, as NodeJS will automatically look for the file in the directory specified by the NODE_PATH environment variable.

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-02-03 11:00:00 +0000

Seen: 7 times

Last updated: Mar 18 '22