【问题标题】:Netlify - Gatsby alias imports not workingNetlify - Gatsby 别名导入不起作用
【发布时间】:2021-12-29 10:37:03
【问题描述】:

我在 Netlify 构建日志中收到此错误:

2:24:32 AM: error Generating JavaScript bundles failed
2:24:32 AM: Can't resolve '@layout/PageContainer' in '/opt/build/repo/src/pages/how-it-works'
2:24:32 AM: If you're trying to use a package make sure that '@layout/PageContainer' is installed. If you're trying to use a local file make sure that the path is correct.
2:24:32 AM: error Generating JavaScript bundles failed
2:24:32 AM: Can't resolve '@pages/HowItWorks' in '/opt/build/repo/src/pages/how-it-works'
2:24:32 AM: If you're trying to use a package make sure that '@pages/HowItWorks' is installed. If you're trying to use a local file make sure that the path is correct.

我已经像这样设置了 webpack 别名:

// gatsby-node.js
exports.onCreateWebpackConfig = ({ stage, actions }) => {
    actions.setWebpackConfig({
        resolve: {
            modules: [path.resolve(__dirname, "src"), "node_modules"],
            alias: {
                "@pages": path.resolve(__dirname, "src/components/pages/"),
                "@layout": path.resolve(__dirname, "src/components/layout/"),
            },
            extensions: [".js", ".json", ".jsx", ".tsx", ".ts"]
        }
    });
};

@pages 文件结构如下:src -> components -> pages

@layout 文件结构如下:src -> components -> layout

我可以在本地 yarn build 我的仓库。没有问题。

一旦我尝试使用 Netlify 进行部署/构建,我就会遇到别名问题。为什么这不适用于 Netlify?

【问题讨论】:

    标签: reactjs webpack gatsby alias netlify


    【解决方案1】:

    我终于让它工作了,但为什么它工作,我不知道!

    我在这方面花费了太多时间并尝试了 100 种不同的东西。Ubuntu 文件系统的行为与 Mac/Windows 非常不同,这就是我能够在本地构建的原因没问题(我使用的是 Windows)。 Netlify 使用 Ubuntu 镜像构建,因此没有其他选择。

    和这里提到的类似:https://github.com/gatsbyjs/gatsby/issues/2897

    这是我为解决我的问题所做的:

    Rename affected directories:
    
    FROM:
    src/components/layout
    src/components/pages
    
    TO:
    src/components/Layout
    src/components/Pages
    
    And then I changed my alias's accordingly:
    
    "@Pages": path.resolve(__dirname, "src/components/Pages")
    "@Layout": path.resolve(__dirname, "src/components/Layout")
    

    在此之后,我将我的更改提交给 git,并在 Netlify 上运行了一个新版本……它就像魔法一样奏效了!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-10
      • 1970-01-01
      • 1970-01-01
      • 2021-04-09
      • 2018-09-26
      • 2018-01-23
      相关资源
      最近更新 更多