Search code examples
reactjswebpackgatsbyaliasnetlify

Netlify - Gatsby alias imports not working


I am getting this error on Netlify build logs:

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.

I have setup webpack alias like so:

// 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 file structure looks like: src -> components -> pages

@layout file structure looks like: src -> components -> layout

I am able to yarn build my repo locally. No issues.

Once I try to deploy/build with Netlify, I get this issue with alias. Why does this not work with Netlify specifically?


Solution

  • I finally got it working, but why it works, I have no clue!!

    From what I found out from spending way too much time on this and trying 100 different things.. Ubuntu file systems behave very different from Macs/Windows which is why I was able to build locally with no issues (I'm using Windows). Netlify only uses Ubuntu image to build, so there was no options of using something else.

    It's similar to what was mentioned here: https://github.com/gatsbyjs/gatsby/issues/2897

    This is what I did to solve my issues:

    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")
    

    After this I committed my changes to git and ran a new build on Netlify... and like magic it worked!