超簡單的react和typescript和引入scss項目搭建流程

一、首先咱們先建立一個react項目,react官網也有react項目搭建的命令css

npx create-react-app my-app
cd my-app

二、安裝咱們項目須要的樣式依賴,這個項目我用的是scsshtml

npm install node-sass -D

  三、安裝typescript的依賴命令node

npm install typescript @types/node @types/react @types/react-dom @types/jest

  四、安裝sass-loader和node-sass依賴react

  

npm install sass-loader node-sass --save-dev

  五、打開react的webpack配置webpack

在node_modules下找到這個文件node_modules/react-scripts/config/webpack.config.dev.js   找到module下的rules,而後找到最後一個配置,修改爲以下的樣子  

  原來的web

{
              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]',
              },
            }

  改以後的typescript

{
                  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']
              },

 

  六、將src裏面的文件改成這樣,並將App.js改成App.tsxnpm

  

 

  index.js代碼以下:json

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

ReactDOM.render(<App />, document.getElementById('root'));

 

  七、在App.tsx裏面寫一些簡單的ts代碼就能夠run了sass

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;

  七、App.scss代碼以下

.content{
    width: 500px;
    height: 500px;
    background-color: pink;
    margin: 0 auto;
    text-align: center;
    line-height: 500px;
    .bth{
        color: blue;
    }
}

 

  七、運行項目執行命令: npm start   //切記 改node_modules裏面的文件 要重啓一下項目

 

相關文章
相關標籤/搜索