【问题标题】:Next.js - webpack aliasing component folders doesn't workNext.js - webpack 别名组件文件夹不起作用
【发布时间】:2017-05-24 14:33:40
【问题描述】:

我正在按照文档中的建议扩展 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'

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

找不到模块“组件/标题”

我的目录结构是这样的:

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

【问题讨论】:

  • 您是否尝试过指定您正在搜索当前文件夹,如下所示: Templates: path.resolve(__dirname, './templates/') ?
  • @SimeonSimeonoff 是的,我有同样的问题。

标签: javascript reactjs webpack next.js


【解决方案1】:

不需要编辑 webpack 文件,而是需要创建 .babelrc 包含这些内容的文件:

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

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

【讨论】:

    【解决方案2】:
    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;
            }
        };
    

    【讨论】:

    猜你喜欢
    • 2017-10-04
    • 2018-06-20
    • 1970-01-01
    • 2021-06-06
    • 2018-10-13
    • 2018-02-08
    • 2021-12-03
    • 2018-02-23
    • 2022-09-27
    相关资源
    最近更新 更多