Next.js: Import components via webpack aliases

Created on 24 May 2017  路  2Comments  路  Source: vercel/next.js

I am extending next.js webpack configuration as suggested in docs.

const path = require('path')

module.exports = {
  webpack: (config, { dev }) => {
    config.resolve = {
      alias: {
        Templates: path.resolve(__dirname, 'templates/'),
        Components: path.resolve(__dirname, 'components/')
      }
    }
    return config
  }
}

I want to make my imports to work like this:

import Template from 'Templates/Base'
import Input from 'Components/Input'

What have I done wrong in configuration because I am getting errors such as:

Cannot find module 'Components/Header'

I am structuring my directory like this:

.git
.next
.storybook
components
|_ Header
|__ index.js
|_ Input
|__ index.js
templates
|_ Base
|__ index.js
pages
|_ index.js
node_modules
containers
stories
...

Most helpful comment

Don't use Webpack for aliases, use Babel, webpack only run for client side code, Babel work client and server side.

You can use babel-plugin-module-alias, and customize your .babelrc.

All 2 comments

Don't use Webpack for aliases, use Babel, webpack only run for client side code, Babel work client and server side.

You can use babel-plugin-module-alias, and customize your .babelrc.

Thanks @sergiodxa that's the best option. Another option is to use webpack aliases with module-alias https://github.com/zeit/next.js/blob/v3-beta/examples/using-preact/server.js

Was this page helpful?
0 / 5 - 0 ratings

Related issues

havefive picture havefive  路  3Comments

timneutkens picture timneutkens  路  3Comments

formula349 picture formula349  路  3Comments

jesselee34 picture jesselee34  路  3Comments

olifante picture olifante  路  3Comments