Absolute paths imports in NextJs
source link: http://www.js-craft.io/blog/absolute-paths-imports-in-nextjs/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Absolute paths imports in NextJs
Do you find yourself writing Nextjs components imports paths like the one below?
import SiteNav from '../../components/common'
export default ()=> {
<SiteNav />
}
If the answer is yes, then you can benefit from the absolute paths imports feature. In order to activate the absolute imports, you will need to edit the contents of jsconfig.json
(or tsconfig.json
if you are using typescript). You will need to set up the compilerOptions.baseUrl
property.
{
"compilerOptions": {
"baseUrl": "."
}
}
If you don't have the jsconfig.json
/tsconfig.json
file created be sure to add it to the root of your project. Also, you will need to restart your dev server in order to see these changes.
Now can remove the ../../
and have a much cleaner import.
import SiteNav from 'components/common'
export default ()=> {
<SiteNav />
}
One nice part is that the old imports will still work.
If your project has a more complex structure you can even declare module aliases. For example, you can say that all the files from the components/ui/buttons
directory are mapped to @/buttons
:
{
"compilerOptions": {
"baseUrl": ".",
"paths": {
"@/buttons/*": ["components/ui/buttons*"]
}
}
}
And after just use this alias in your js files:
import MyButton from '@/buttons/MyButton'
I hope you have enjoyed this article and if you would like to get more articles about React and frontend development you can always sign up for my email list.
Newsletter subscribe:
Recommend
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK