Absolute imports in Next.js


When I was working on my first project with Next.js I spent a lot of time to find how to use absolute imports. The solution turned out to be quite simple. You need to indicate this resolve option in your next.config.js file:


module.exports = {

  webpack(config) {

    config.resolve.modules.push(__dirname)

    return config;

  },

}

Or if you want to add absolute path only for one directory you can use alias:


module.exports = {

  webpack(config) {

    config.resolve.alias['components'] = path.join(__dirname, 'components');

    return config;

  },

}


Dmitry
Sokolov

Frontend Developer at JetRockets

Explore more of JetRockets