Next.js - webpack 别名组件文件夹不起作用

Next.js - webpack aliasing component folders doesn't work

我正在按照文档中的建议扩展 next.js webpack 配置。

const path = require('path')

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

我想让我的导入像这样工作:

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

我在配置中做错了什么,因为我收到如下错误:

Cannot find module 'Components/Header'

我正在这样构建我的目录:

.next
.storybook
components
|_ Header
|__ index.js
|_ Input
|__ index.js
templates
|_ Base
|__ index.js
pages
|_ index.js
node_modules
containers
stories
...
const path = require("path");

    module.exports = {

        webpack: function(config, { dev }) {

            config.resolve.alias = {
                Templates: path.resolve(__dirname, "templates/"),
                Components: path.resolve(__dirname, "components/")
            };

        return config;
        }
    };

不需要编辑 webpack 文件,而是需要使用以下内容创建 .babelrc 文件:

{
  "plugins": [
    ["module-alias", [
      { "src": "./components", "expose": "Components" },
      { "src": "./containers", "expose": "Containers" },
      { "src": "./templates", "expose": "Templates" }
    ]]
  ],
  "presets": [
    "es2015",
    "next/babel"
  ]
}

这样我们扩展了 Next.js .babelrc 配置并且它在服务器端也能很好地工作。