React: Import CSS – Unexpected Token

React logo

React is a Javascript framework growing in popularity by the day. Open sourced by Facebook a few years ago, its reach has stretched far and wide.

Most developers starting off with React will start with the create-react-app boilerplate provided by Facebook. However as time goes on and your experience grows, you naturally want to move away and take control of some of the complexity hidden by create-react-app – such as the Webpack and Babel configuration.

However, as a developer used to create-react-app, you can suddenly start hitting a load of new bricks walls as you go it alone and start to have to make considerations you never used to have to.

One of those, is importing static files – particularly if your adopting an isomorphic route to render your shiny new single page app server-side.

One of the common errors is that caused by importing cascading style sheets (CSS).

Can’t I Include My Style Directly In React Components

Yes. But as with other languages, you’ll probably prefer having separate stylesheets that you import allowing you to keep your components code readable.

The Import

You’ve probably got something like this:

import "./Header.css";

Simple, eh? Include this stylesheet.

Oh no, error time. Try to run it and you’re hit with a brick wall:

SyntaxError: F:/Ampps/www/GitLab/DPSComputing/Experiment/isomorphic-react/src/Components/fragments/Header.css: Unexpected token (1:0)
1 | .logo {
  | ^
2 | max-height: 100px;
3 | }

The first character it encounters in the file and boom – fallover time!

There are many solutions out there on the web, many ludicrously complex. Here we’ve got the addition of one node module dependency and one additional line of Babel configuration that’ll get you on your way.

Fixing CSS Unexpected Token in React

You need a new module for babel – css modules tranform – adding to your project development depdencies. Run the following command:

npm install --save-dev babel-plugin-css-modules-transform

After the install is complete, open your .babelrc file, and in the plugins section add “css-modules-transform”, like so:

 "plugins": [
    "transform-object-rest-spread",
    "css-modules-transform"
  ]

NPM start again, and your CSS files will now be being installed without issue!

You may also like...

%d bloggers like this: