linaria icon indicating copy to clipboard operation
linaria copied to clipboard

SyntaxError when using styled custom components in Next.js

Open mcamis opened this issue 4 years ago • 4 comments

Environment

  • Linaria version:
    • "@linaria/core": "^3.0.0-beta.4"
    • "@linaria/react": "^3.0.0-beta.7,
    • "@linaria/babel-preset": "^3.0.0-beta.4"
    • "@linaria/shaker": "^3.0.0-beta.7"
    • "@linaria/webpack-loader": "^3.0.0-beta.7"
  • Bundler (+ version):
    • Next.js 10.0/Webpack 4
    • "next-linaria": "1.0.0-beta"
  • Node.js version:
    • 14.15.15
  • OS:
    • macOS Big Sur

Description

Using the example for styled custom components in the docs ( see CoolComponent), we're getting a SyntaxError as seen below

import React from ;
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at transformFile.next (<anonymous>)
It may happen when your code or third party module is invalid or uses identifiers not available in Node environment, eg. window. 
Note that line numbers in above stack trace will most likely not match, because Linaria needed to transform your code a bit.

Reproducible Demo

Simplified Next.js app to demo this:

  • https://github.com/mcamis/linaria-custom-component-example
  • https://codesandbox.io/s/quizzical-water-tl1hn?file=/pages/index.js

mcamis avatar Aug 10 '21 17:08 mcamis

@mcamis

npm i -D @babel/plugin-transform-react-jsx

or

yarn add -D @babel/plugin-transform-react-jsx

.babel.rc

{
  "presets": ["next/babel", "@linaria"],
  "plugins": [
    [
      "@babel/plugin-transform-react-jsx",
      {
        "runtime": "automatic"
      }
    ]
  ]
}

hope this helps

s-r-x avatar Aug 11 '21 15:08 s-r-x

@s-r-x That did the trick, thank you! 🎉

Is the underlying issue here that next's babel config isn't directly compatible with linaria (or vice versa)?

mcamis avatar Aug 11 '21 16:08 mcamis

@mcamis i'm not quire sure tbh. i've just played a little bit with your example and found out that React.createElement works, but jsx syntax is not. So i thought that the reason of that was the new-ish react 17 jsx transform. i don't think that configs are fully incompatible. linaria just don't know about this automatic runtime rule from next preset when it transpiling custom components, so it has to be inserted manually

s-r-x avatar Aug 11 '21 16:08 s-r-x

Does anyone know how to configure it in Vite? I'm using @linaria/rollup plugin and can't feed the babelrc plugin.

zheeeng avatar Oct 26 '21 14:10 zheeeng