How do I configure NextJS to correctly handle alias paths within scss?
Asked Answered
E

1

16

I've created a nextjs app within my NX monorepo and I've started porting an existing NX app (within the same monorepo) to it.

My NX monorepo is set up with many alias's, all of them configured within the root tsconfig.base.json file. For instance, I keep all my images in an images library and I load them like this from within JSX:

import myImage from '@images/myImage.png';

This is how I use the aliases from within a SCSS file:

background-image: url('@images/myImage.png');

Both of these work within my existing Non-Nextjs app, however, when I port my app over to the new Nextjs app, the aliases used within url() are not recognized. The errors I get look like this:

Module not found: Can't resolve '../themes/@images/myImage.png'

Note, my css file lives in ./themes and so it's treating the aliased @images/... urls as relative paths and appending them to the current file location.

What is the recommended approach for having the aliased paths handled correctly when used within scss?

Evette answered 9/5, 2022 at 23:41 Comment(1)
hi ! did you find any answers to this?Antarctic
P
0

Aliases for TypeScript and for SCSS have to be configured separately.


For SCSS you have to configure aliases in the webpack config.

In Next.js you can modify webpack config in next.config.js:

/** @type {import('next').NextConfig} */
const nextConfig = {
    webpack: (config) =>
    {
        // in my version (v13) I had to write ./@images
        // in your version it may be possible to instead write @images
        config.resolve.alias['./@images'] = '/path/to/images';
        // config.resolve.alias['@images'] = '/path/to/images';

        // in some cases you may need to use path.resolve, but normally it should work without it
        // config.resolve.alias['./@images'] = path.resolve(__dirname, './path/to/images');

        return config;
    }
}

For projects other than next.js you would usually have a webpack.config.js and there you would do:

module.exports = {
    resolve: {
        alias: {
            '@images': '/path/to/images'
        }
    }
}

You can read more about aliases in webpack on the official docs.


For TypeScript you already seen that you can configure aliases in tsconfig.json:

{
  "compilerOptions": {
    "paths": {
      "@images/*": ["/path/to/images/*"],
    }
  }
}
Peony answered 24/12, 2023 at 16:13 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.