25

How do i include "css" file in "tsx" and how to use it? i.e how do i render static files?

import * as React from "react";
import { Header } from "./header";

//import "./home.css";


export class Home extends React.Component<{}, {}> {
    render() {
        return (
            <div id="page-top" className="landing-page">
                <Header />
            </div>
        );
    }
}
2
  • what do you want to make with the css file? in general it should be available if you included it before in HTML Commented Jan 13, 2017 at 6:00
  • it will work if i include css scripts in index.html bt i want to use it in jsx in tsx file Commented Jan 13, 2017 at 6:13

5 Answers 5

15

You cannot directly import CSS or any other static files into typescript using only the typescript compiler, but you can with the help of some build tools...

For example using webpack, you can set up the css-loader and style-loader to search your source code for require('./whatever.css') and add it to the build before safely compiling your typescript. If you also have webpack generate your HTML then your CSS will be automatically injected as a stylesheet.

Sign up to request clarification or add additional context in comments.

7 Comments

but 'require' doesn't work in tsx , import './whatever.css' works, also how to do what you have mentioned in the last line
import should work, as long as you don't want to assign it to anything. If you do (ie if using CSS modules) then for the signature of require to not give you typescript warnings add the @types/node definitions to your project. Without any of your build config it is hard to give precise instructions to achieve your goal - there are plenty of resources available to help get webpack set up if you haven't already. The loaders you need will need are css-loader, and typescript-loader
hey thanx i added css-loader and file-loader(for images), it works, but how to serve js scripts to html automatically
Excellent. You can use the html-webpack-plugin to generate your html, which will automatically put any script and css link tags in there. If you have extra stuff currently that you still want to control you can pass it a template file... ` const HtmlWebpackPlugin = require('html-webpack-plugin') /* in the webpack config object */ plugins: [ new HtmlWebpackPlugin({ template: './src/index.template.ejs', inject: 'head' }) ] `
|
15

See this answer:

https://stackoverflow.com/a/37144690/3850405

If you only need css for a class in your component you could do it like below. I like this solution for when inline css does not work and only small changes are needed.

import * as React from "react";
import { Header } from "./header";

export class Home extends React.Component<{}, {}> {
    render() {
        const css = `
        .landing-page {
            background-color: orange;
        }
        `
        return (
            <div>
                <style>
                    {css}
                </style>
                <div id="page-top" className="landing-page">
                    <Header />
                </div>
            </div>  
        );
    }
}

5 Comments

See my answer above
@xumix I don't understand your downvote. Your solution requires webpack and answers a question about typings - which the question is not about. I'm providing a link to a solution with webpack and giving an example without having to use a separate css-file.
The question is 1) about typescript, not js as your provided link 2) your answer is about adding inline styles but not including a css file into a tsx
Let's agree to disagree then. 1) .Typescript yes since it is a .tsx file but the question is not about typings. 2) I still think my answer is a viable solution that does not require external dependencies. My link also provides an answer to including a .css-file - I do not like to duplicate another answer when it already exist.
"See my answer above – xumix Nov 22, 2017 at 10:00" it is now "below" here from users voting
11

I've stumbled upon this question today also and found that TS now can import css directly with webpack and awesome-typescript-loader exactly like this:

import "./home.css";

But if you like me want to use CSS modules, than you will have to add some more steps:

  1. npm install --save-dev typings-for-css-modules-loader
  2. Change your css-loader to typings-for-css-modules-loader
  3. Change your webpack config to smth like this:

```

module: {
    rules: [
        { test: /\.tsx?$/, include: /ClientApp/, use: 'awesome-typescript-loader?silent=true' },
        { test: /\.css$/, use: isDevBuild ? ['style-loader', "typings-for-css-modules-loader?namedExport&modules"] : ExtractTextPlugin.extract({ use: 'typings-for-css-modules-loader?minimize&namedExport&modules' }) },
        { test: /\.(png|jpg|jpeg|gif|svg)$/, use: 'url-loader?limit=1000' }
    ]
}

This will generate typings for css files and you will be able to use them like

import * as style from './home.css';

Here is the article I used for my config: https://medium.com/@sapegin/css-modules-with-typescript-and-webpack-6b221ebe5f10

Comments

0

I recently had this problem when converting my projects from JavaScript to TypeScript and I tell you that the solution is very simple. just create a file as “global.d.ts” in the src directory of your project, in the file global.d.ts you must write the following: declare module “*.css”; that way vite will recognize files with .css extension.

Comments

-1

I went through a lot of related questions/answers and external articles before finally finding a step-by-step walkthrough. While the answer by [alechill] eventually got me to my solution, I thought I would drop in my detailed solution for anyone that finds this post...

npm install sass-loader css-loader style-loader --save // this may differ

edit webpack.config.js to add a rule and an extension to resolve scss

module.exports = {
    /* stuff */
    module: {
        rules: [
            /* other rules, */
            {
                test: /\.scss$/,
                use: ['style-loader', 'css-loader', 'sass-loader']
            }
        ]
      },
      resolve: {
          extensions: [/* file extensions, */ '.scss']
      },
    },
    /* more stuff */
};

create/edit declaration.d.ts

declare module '*.scss' {
    const content: { [className: string]: string };
    export = content; // your IDE may warn of "no usages" here, mine did
}

Make it happen...

SomeComponent.tsx

import React from 'react';
import './SomeComponent.scss';

interface Props { /* ... */ }
interface State { /* ... */ }

class SomeComponent extends React.Component<Props, State> {
    /* do awesome stuff */
}

SomeComponent.scss

body {
    h1,h2,h3,h4,h5 {
        background-color: red; /* test that it works */
    }
}

Build and enjoy!

File structure described above

src/SomeComponent.tsx
src/SomeComponent.scss
declaration.d.ts
webpack.config.js

I'm still learning react typescript, so refactoring .scss files into the src/styles directory as an alias is, at this point, an exercise left to you

1 Comment

I think it is better to always refer to the webpack doc because these things change.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.