0

I wanted to give Linaria (utilizing next-linaria) a try, but I'm currently stuck to get it working in any of my Next.js projects (that also use Typescript by the way).

The root of evil seems to be path aliases that are supported by Next.js by default.

tsconfig.json

  ...
  "compilerOptions": {
    ...
    "paths": {
      "~/*": [
        "src/*"
      ]
    }
  },

When just installing Linaria and next-linaria, I get an error like this:

Error: Can't resolve '~/layout/main/MainWrapper' in '[...]\src\layout\main'

I already know that Linaria stated to not support any other module aliasing than @babel-plugin-module-resolver or webpack. However, I can't get either of those to work.

I tried @babel-plugin-module-resolver and put same path configuration (and some other tries) to .babelrc without success.

  "plugins": [
    ["module-resolver", {
      "alias": {
        "~/*": [
          "src/*"
        ]
      }
    }]
  ]

I also tried doing the same with webpack aliases.

next.config.js

module.exports = withLinaria({
  webpack: (config, { dev }) => {
    config.resolve.alias = {
      ...config.resolve.alias,
      "~/": path.resolve(__dirname, "./src/"),
    };
    return config;
  },
});

The default project structure of Next.js looks like this:

/
/pages (contains entry points for each route)
/src (contains regular react components)

So, I'm kindly asking if anyone can tell us how to use path aliasing with Next + Linaria.

K. D.
  • 4,041
  • 9
  • 48
  • 72
  • Try specifying `extensions` and `root` too in babelrc. Like this: ```["babel-plugin-module-resolver", { "root": ["./src/"], extensions: [".jsx"], alias: {"~": "."} }]``` – brc-dd Aug 02 '21 at 11:42
  • Thank you @brc-dd. I get another error now, because with Next.js, all pages are within a `pages/` folder outside of `src/`, so specifying `src/` for `root` seems to be an issue. I tried this, but then I get the same error as before: `"plugins":[["babel-plugin-module-resolver",{"root":["."],"extensions":[".jsx"],"alias":{"~/":"./src/"}}]]` – K. D. Aug 02 '21 at 14:10
  • Just change `"./src/"` in my comment above to `"./"` -- keep other things same (change the extensions array to whatever format(s) you are using). Basically in alias you don't have to put trailing slash. Add your project structure to the question itself for a more precise answer. – brc-dd Aug 02 '21 at 14:13
  • 1
    Thank you. I have edited the default structure. I guess your code is correct, except that we have to link `~` to `./src`. Now the `"Could not resolve"` issue goes away, but instead I get an `Unknown word` issue. However, I'll try to fix that myself first. Thank you so far. – K. D. Aug 02 '21 at 14:24

0 Answers0