JoeTidee
JoeTidee

Reputation: 26034

How to have absolute require / import paths to the project root?

I want all the paths in my application to be relative to my project root, so that I don't have to do:

import foo from "../../bar.js";
var foo = require("../../bar.js");

My client side of the application is compiled using Webpack, so I imagine that I can use the 'resolve' facility in the Webpack, but would prefer not to as this adds a dependency to using Webpack. The backend uses an Node/Express server.

Is there a solution that works in both front and back-end?

Upvotes: 2

Views: 1258

Answers (1)

idbehold
idbehold

Reputation: 17168

In your package.json add ln -fsn ../ 'node_modules/>' at the following JSON path scripts.postinstall:

{
  "scripts": {
    "postinstall": "ln -fsn ../ 'node_modules/>'"
  }
}

This will create a symbolic link named > in your project's node_modules which is pointing to your project's root folder.

Assuming your file structure looked like this:

project
├── bar.js
├── config
│   ├── database.js
│   ├── rabbitmq.js
│   └── env.js
├── seed
│   ├── soy.js
│   ├── wheat.js
│   ├── pumpkin.js
│   └── squash.js
├── foo
│   └── bar
│       └── baz
│           └── qux.js
├── index.js
└── package.json

From inside the foo/bar/baz/qux.js file we could require the seed/soy.js file like this:

require('>/seed/soy')

Upvotes: 2

Related Questions