CSS import aliases with Next.js

879 Views Asked by At

There are many solutions floating around regarding import aliases within JavaScript/TypeScript files using Next.js

Does anyone have a working example of something similar with CSS?

For example, I have an alias @Styles that I have in the tsconfig.json as

"baseUrl": ".",
"paths": {
  "@/*": ["./src/*"],
  "@Components/*": ["./src/components/*"],
  "@Components": ["./src/components"],
  "@Icons/*": ["./src/components/Icons/*"],
  "@Icons": ["./src/components/Icons"],
  "@Images/*": ["./src/assets/images/*"],
  "@Images": ["./src/assets/images"],
  "@Styles/*": ["./src/assets/styles/*"],
  "@Styles": ["./src/assets/styles"]
}

In a CSS file, I try to do something like this @import '@Styles/layout.css';. This doesn't work.

postcss.config.js looks like this:

const path = require('path');
module.exports = {
  plugins: {
    'postcss-import': {
      root: path.resolve(__dirname, 'src'),
      path: ['assets'],
      skipDuplicates: true
    },
    'postcss-nesting': {},
    'postcss-custom-media': {},
    'autoprefixer': {}
  }
};

Can someone help guide what am I missing to configure CSS postcss-import aliases? Is this possible with Next.js?

1

There are 1 best solutions below

0
On

Given the CSS import statement @import '@Styles/layout.css'; the configuration below resolves to that CSS import:

//postcss.config.js
const path = require('path');


const aliasMapping = {
  '@Styles': (filename) => path.resolve(__dirname, `src/assets/styles/${filename}`),
  '@Images': (filename) => path.resolve(__dirname, `src/assets/images/${filename}`)
};


module.exports = {
  plugins: {
    'postcss-import': {
      root: path.resolve(__dirname, 'src'),
      path: ['assets'],
      skipDuplicates: true,
      resolve: (id, basedir, importOptions) => {
        const [aliasName, filename] = id.split('/');
        return aliasMapping[aliasName](filename);
      }
    },
    'postcss-nesting': {},
    'postcss-custom-media': {},
    'autoprefixer': {}
  }
};

Now any CSS file can implement an import alias successfully. In the aliasMapping you just continue to add aliases as needed.