How do i include "css" file in "tsx" and how to use it? ie 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>
);
}
}
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:
npm install --save-dev typings-for-css-modules-loader
css-loader
to typings-for-css-modules-loader
```
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
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.
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>
);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.