I’m trying to adapt a Next.js template to start a new project. However, this type of import which I have seen in previous projects.
import config from "@config/config.json";
import theme from "@config/theme.json";
I would like to know how to do this type of import with @. What term should I search the documentation with to achieve this?
I would appreciate any explanation.
4
Answers
create a jsconfig.json at root of your directory and
Enjoy
if you use React Typescript, to create shortcut/alias first you need to add a file at root folder called
tsconfig.base.json
if doesn’t exist there, then, add your shortcuts as the example given below:These imports are used by scoped npm packages.
To make use of an import like these, there should be an npm package with the scope/name that you are using.
You can have locally something like this:
Then you should create a directory with name "@config".
This type of importing in JavaScript that starts with the "@" symbol is known as "Relative Import." Using "@" at the beginning of a path signifies that the path is relative to project-specific names or aliases and not absolute paths.
To achieve this type of import with the "@" symbol in Next.js, you can take advantage of module path aliases. This feature allows you to define custom aliases for specific paths, making it easier to import modules in your code.
To set up module path aliases in Next.js, you need to create or modify a configuration file named "next.config.js" in the root of your project. Here’s how you can do it:
Create or open the "next.config.js" file.
Inside the file, you can use the "module.exports" object to specify your custom path aliases. You’ll use the "webpack" property and define the "alias" object as follows:
Replace ‘path/to/your/config/files’ with the actual path to the folder where your config files, such as "config.json" and "theme.json," are located. Make sure to provide the correct path relative to the root of your project.
Save the "next.config.js" file.
With this configuration, Next.js will map the "@config" alias to the specified folder, and you’ll be able to import modules using the "@" symbol in your code, just like in your example:
Now, when you start your Next.js project, it should recognize the custom path aliases, and the imports with "@" should work correctly.
Please note that setting up custom path aliases in Next.js might require you to restart the development server for the changes to take effect. Additionally, make sure to use the correct path and folder structure to ensure successful imports.