Can't import styled components in the "starter-react" project

I just had to help a user who ran into an issue with the default “starter-react” project. They were using styled-components, and all of the styled JS docs use import statements, which crash the starter-react project:

(Example here:!/sepia-azimuth?path=app/components/HelloWorld.jsx:4:0)

Hash: 3cb2ee22dc8fc269371d
Version: webpack 4.30.0
Time: 2948ms
Built at: 2019-08-21 16:12:47
 1 asset
Entrypoint main = bundle.js
[2] ./app/app.jsx 240 bytes {0} [built]
[8] (webpack)/buildin/global.js 472 bytes {0} [built]
    + 8 hidden modules

ERROR in ./app/components/HelloWorld.jsx
Module build failed (from /rbd/pnpm-volume/aaef42b4-671c-43d6-94fc-008c9a0105ea/node_modules/
Error: Parse Error: Line 2: Illegal import declaration
    at throwError (/rbd/pnpm-volume/aaef42b4-671c-43d6-94fc-008c9a0105ea/node_modules/
    at throwErrorTolerant (/rbd/pnpm-volume/aaef42b4-671c-43d6-94fc-008c9a0105ea/node_modules/
    at parseSourceElement (/rbd/pnpm-volume/aaef42b4-671c-43d6-94fc-008c9a0105ea/node_modules/
    at parseProgramElement (/rbd/pnpm-volume/aaef42b4-671c-43d6-94fc-008c9a0105ea/node_modules/
    at parseProgramElements (/rbd/pnpm-volume/aaef42b4-671c-43d6-94fc-008c9a0105ea/node_modules/
    at parseProgram (/rbd/pnpm-volume/aaef42b4-671c-43d6-94fc-008c9a0105ea/node_modules/
    at Object.parse (/rbd/pnpm-volume/aaef42b4-671c-43d6-94fc-008c9a0105ea/node_modules/
    at getAstForSource (/rbd/pnpm-volume/aaef42b4-671c-43d6-94fc-008c9a0105ea/node_modules/
    at Object.transform (/rbd/pnpm-volume/aaef42b4-671c-43d6-94fc-008c9a0105ea/node_modules/
    at Object.transform (/rbd/pnpm-volume/aaef42b4-671c-43d6-94fc-008c9a0105ea/node_modules/
    at Object.module.exports (/rbd/pnpm-volume/aaef42b4-671c-43d6-94fc-008c9a0105ea/node_modules/
 @ ./app/app.jsx 5:19-53

styled components is an es6 module, so if a user tries to rewrite this to a require call, they get a confusing error:

Uncaught TypeError: n(...).div is not a function

(The user I was helping had gotten this far, but couldn’t figure out the error)

The only workaround is to know internally how es6 modules work and rewrite your code to take that into account:

const styled = require('styled-components').default;

which is a lot to expect of a normal starter react user!

Ideally we should fix the webpack configuration for the starter-react project so that it supports es6 import statements, or at least is smart enough to handle es6 modules when you call require() (i’m pretty sure webpack has configuration options for both of these, but I don’t know them off the top of my head)

Hey @nightpool thanks for the info! I’ll pass this along to the folks who maintain the starter apps for them to consider!

1 Like