In the Next.js 9 tutorial the suggested way to import shared components is by relative paths, like
import Header from '../components/Header';
I want to use absolute imports, like
import Header from 'components/Header';
How do I make this work both locally and when I deploy using the Now CLI?
Using the suggested setup from the tutorial, my project structure is:
my-project
├── components
├── pages
└── package.json
If you're using Next.js 9.4 or later, see Black's answer.
There are different ways of achieving this, but one way – that requires no additional dependencies and not too much config – is to set the environment variable NODE_PATH
to the current directory, i.e. NODE_PATH=.
.
I think the easiest way to set NODE_PATH=.
when running the dev/build scripts in your package.json
locally (e.g. $ npm run dev
or $ yarn dev
), is to add it to each script in package.json
:
"scripts": {
"dev": "NODE_PATH=. next",
"build": "NODE_PATH=. next build",
"start": "next start"
},
When you deploy to ZEIT Now, NODE_PATH
must be set in a different way.
You can add a Deployment Configuration by adding a now.json
file (it should be in the same directory as your package.json
). If you don't have a now.json
file already, create it and add the following contents:
{
"version": 2,
"build": {
"env": {
"NODE_PATH": "."
}
}
}
This tells Now to use NODE_PATH=.
when buildnig your app (see build.env).
(It also tells Now that we use Now platform version 2 which is currently the newest version (see version). Omitting the version will give you a warning when you deploy using $ now
.)
In Next.js 9.4 it is possible to do it by adding the baseUrl
config to jsconfig.json
(JS projects) or tsconfig.json
(TS projects).
// jsconfig.json or tsconfig.json
{
"compilerOptions": {
"baseUrl": "."
}
}
This will allow imports from the root directory. It also integrates well with IDE such as VS Code. See documentation for more information.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With