1、首先我们先创建一个react项目,react官网也有react项目搭建的命令
npx create-react-app my-app
cd my-app
2、安装我们项目需要的样式依赖,这个项目我用的是scss
npm install node-sass -D
3、安装typescript的依赖命令
npm install typescript @types/node @types/react @types/react-dom @types/jest
4、安装sass-loader和node-sass依赖
npm install sass-loader node-sass --save-dev
5、打开react的webpack配置
在node_modules下找到这个文件node_modules/react-scripts/config/webpack.config.dev.js 找到module下的rules,然后找到最后一个配置,修改成如下的样子
原来的
{ loader: require.resolve('file-loader'), // Exclude `js` files to keep "css" loader working as it injects // its runtime that would otherwise be processed through "file" loader. // Also exclude `html` and `json` extensions so they get processed // by webpacks internal loaders. exclude: [/.(js|mjs|jsx|ts|tsx)$/, /.html$/, /.json$/], options: { name: 'static/media/[name].[hash:8].[ext]', }, }
改之后的
{ exclude: [/.js$/,/.html$/,/.json$/,/.scss$/], loader: require.resolve('file-loader'), options: { name: 'static/media/[name].[hash:8].[ext]', }, }, { test:/.scss$/, loaders:['style-loader','css-loader','sass-loader'] },
6、将src里面的文件改为这样,并将App.js改为App.tsx
index.js代码如下:
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.render(<App />, document.getElementById('root'));
7、在App.tsx里面写一些简单的ts代码就可以run了
import React, { Component } from 'react';
import './App.scss'; //引入当前文件scss
interface Props { } interface State { list: string, } class App extends Component<Props, State> { constructor(props: Props) { super(props) this.state = { list: 'hello world!!!' } } render() { return (
<div className="content">
<div className="btn">{this.state.list}</div>
</div>
); } } export default App;
7、App.scss代码如下
.content{ 500px; height: 500px; background-color: pink; margin: 0 auto; text-align: center; line-height: 500px; .bth{ color: blue; } }
7、运行项目执行命令: npm start //切记 改node_modules里面的文件 要重启一下项目