4

I'm constantly hitting a wall, when In try to use NextJS with react-native-web and styled-components.

The issues SEEMS to be something related to improper aliasing of "react-native" from within styled-components. I'm unsure how to solve it though.

I know how to make it work with Razzle.js, but I can't for the life of me figure out how to get to the same working state with NextJS. My suspicion is that it has to do with webpack's config.externals - BUT it could also be something in babel.config.js.

If someone has tackled this issue, you'll be my favourite person of the year. I've setup to repo's reproducing the issue

--- Next.js
pages/index.js - WORKS
pages/problem.js - FAILS (has styled-components/native)

--- Razzle
pages/Home.js - WORKS
pages/Home.js - WORKS (has styled-components/native)

https://github.com/Aleksion/rnw-styled-next https://github.com/Aleksion/rnw-styled-razzle

AHerforth
  • 125
  • 1
  • 2
  • 7

1 Answers1

6

I had googled, and found this case too.. And the solution is install next-transpile-modules and config your next.config.js like below

const withTM = require('next-transpile-modules')

module.exports = withTM({
    transpileModules: [
      "react-native", "styled-components", "styled-components/native"
    ],
    webpack: config => {
      return {
        ...config,
        resolve: {
          ...config.resolve,
          extensions: [
            '.web.ts',
            '.web.tsx',
            '.ts',
            '.tsx',
            '.web.js',
            '.web.jsx',
            '.js',
            '.jsx',
            ...config.resolve.extensions
          ],
          alias: {
            ...config.resolve.alias,
            'react-native$': 'react-native-web'
          }
        }
      }
    }
  })

And the result :

enter image description here

Hope it will save your day :)

Forte Zhuo
  • 231
  • 3
  • 12
  • Yep, spot on. Thank you for reminding me to follow up on this. I got it working and everything works... ok. I just forgot to update this. I still experience some issues with it not compiling and treeshaking properly but it works. So that's a start. – AHerforth Sep 28 '19 at 00:49
  • This doesn't work now. What worked was remove `transpileModules` inside `withTM()` then use `const withTM = require('next-transpile-modules')["styled-components", "styled-components/native"]`. See docs for more info: https://github.com/martpie/next-transpile-modules#scoped-packages – dcangulo Sep 05 '20 at 06:24