Adding CSS Support for TypeScript React
- By : Mydatahack
- Category : Front-End, Web Technologies
- Tags: CSS, React, TypeScript
Let’s extend the previously build Webpack TypeScript React project to include CSS support. For a small application or widget, it is better to bundle CSS with JavaScript code. This post focuses on getting Bootstrap and styled-jsx working for a React project with TypeScript.
Styled-jsx enables us to inject CSS style as a react component. You can create a react component returns the style tag with inline css. See example here.
(1) Install dependencies
npm i --save bootstrap npm i --save-dev style-loader css-loader npm i styled-jsx --save
(2) Update webpack.config
We need to add style-loader and css-loader. The style-loader must be loaded first. Otherwise, you will get an error.
module: { rules: [ { test: /\.tsx?$/, exclude: /node_modules/, loader: "ts-loader"}, { test: /\.js$/, use: ["source-map-loader"], enforce: "pre" }, { test: /\.css$/, use: ['style-loader', 'css-loader']} ] },
(3) Adding bootstrap support
create css folder in the public folder and import with bootstrap.css file first, then import it in index.tsx file where you have ReactDom.render() method. In this way, bootstrap will get compiled into a bundle.
bootstrap.css
@import "../../node_modules/bootstrap/dist/css/bootstrap.css";
index.tsx
import '../public/css/bootstrap.css'
(4) Get styled-jsx work
Styled-jsx takes two attributes in the style element, jsx and global as style jsx global. As TypeScript does not know their types, it complains. To add types for these attributes, we can add the definitions in the custom.d.ts file in the src folder.
Everything should work smoothly now. For more complete example, please check out this repo.