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{ width: 500px; height: 500px; background-color: pink; margin: 0 auto; text-align: center; line-height: 500px; .bth{ color: blue; } }
7、運行項目執行命令: npm start //切記 改node_modules里面的文件 要重啟一下項目

