t> 前几天给准备了一些简单的简单的React教程,之前在做团队项目的时候,用了大佬们的框架,直接刷刷写就OK,可是当自己去配置一些东西的时候,发现事情并没有那么简单,用了两天的时间反复折腾一些UI,配置TypeScript,每一步都十分艰辛

创建React项目

这里我们首先采用FaceBook制作的Create-React—App 这个Cli,用脚手架的原因就是,比较方便嘛,先配制出一个架子来,以后慢慢深入,自己造轮子?当然,造轮子是对个人技术的检验和学习,也并非会用于正式生产

通过creat-react-app 创建一个React项目

Quick Overview

  • 创建React项目

    1. npx

      npx create-react-app my-app

(npx comes with npm 5.2+ and higher, see instructions for older npm versions)

  1. npm

    npm init react-app my-app

npm init is available in npm 6+

  1. Yarn

    yarn create react-app my-app

(npx comes with npm 5.2+ and higher, see instructions for older npm versions )

Then open http://localhost:3000/ to see your app.
When you’re ready to deploy to production, create a minified bundle with npm run build.

demo

通过creat-react-app创建TypeScript项目

create-react-app my-app --scripts-version=react-scripts-ts

在这里我们采用这个,并且使用yarn安装,为后续TypeScript项目提供支持

安装对Stylus的支持

创建完项目后,要执行yarn eject (npm 安装执行npm eject) 也就是打开全部配置项。

安装依赖:yarn add stylus stylus-loader

找到config里面的两个配置文档。

配置的内容都是一样的。

关于stylus不多解释,网上太多了。文档后缀是 .styl

修改webpack.config.prod.js

  • 找到oneOf:[]

在里面按照模板内容添加

{ 
  test: /\.styl$/, 
  loaders: ['style-loader', 'css-loader', 'stylus-loader'], 
},
  • 找到file-loader

对照修改为以下内容

{
  loader: require.resolve('file-loader'),
  // Exclude `js` files to keep "css" loader working as it injects
  // it's runtime that would otherwise processed through "file" loader.
  // Also exclude `html` and `json` extensions so they get processed
  // by webpacks internal loaders.
  exclude: [/\.(js|jsx|mjs)$/, /\.html$/, /\.json$/ ,/\.styl$/],
  options: {
              name: 'static/media/[name].[hash:8].[ext]',
            },
},

修改webpack.config.dev.js

与修改webpack.config.dev.js相同

Stylus快速调用

在前端项目根目录中,新建文件lib.d.ts

// 这个文件定义了一些特殊文件的类型描述

declare module "*.styl" {
  interface IClassNames {
    [className: string]: string
  }
  const classNames: IClassNames;
  export = classNames;
}

Stylus的使用

import * as React from 'react';
import * as Style from './MessageCenter.styl'
import { RefreshProgress } from "../views/Refresh";
export class MessageCenter extends React.Component {
  private isRender: boolean = false
  public render() {
    if (this.isRender) {
      return (
        <div className={Style.Container}>
          <div className={Style.Content}>
            <div className={Style.List}>HelloWorld</div>
          </div>
        </div>
      );
    }
    else {
      return (
        <div><RefreshProgress /></div>
      )
    }
  }

  componentDidMount() {
    if (!this.isRender) {
      setTimeout(
        () => {
          this.isRender = true
          this.setState({})
        }, 1000)
    }

  }
}

资料下载

创建完项目后,要执行yarn eject

安装依赖:yarn stylus stylus-loader

可以直接下载下面两个文件复制到config

webpack.config.dev.js
webpack.config.prod.js

lib.d.ts

以上为CDN存储,右击另存为,如链接失效可留言

注意:另存为下载可能会对其重命名,下载后需要按照正确的名字命名