美文网首页
react项目搭建

react项目搭建

作者: lovinglili | 来源:发表于2019-05-07 15:07 被阅读0次

1. 安装脚手架 create-react-app

  • sudo npm install -g create-react-app

2.创建 react 项目

  • create-react-app my-app

3. 目录结构

image.png
  • cd my-app
  • npm start

4. 自定义配置工具 react-app-rewired 2.0版本

  • npm install react-app-rewired --save-dev
  • my-app 下创建文件 名为 config-overrides.js
  • package.json 更改为:
  "scripts": {
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test",
    "eject": "react-app-rewired eject",
  },

5. 使用 ant.design,使用模块化css

  • react-app-rewired 2.0版本要使用 customize-cra

  • 安装babel-plugin-import,less,less-loader

  • css/less文件命名为:xx.module.less/css


    image.png
  • 接入之后,config-overrides.js内容如下:

const {
  override,
  fixBabelImports,
  addWebpackAlias,
  addLessLoader
} = require("customize-cra");
const PATH = require("path");
function resolve(url) {
  return PATH.resolve(__dirname, "src/", url);
}

module.exports = override(
  fixBabelImports("import", {
    libraryName: "antd",
    libraryDirectory: "es",
    style: true
  }),
  addWebpackAlias({
    "@c": resolve("component"),
    "@pages": resolve("pages"),
    "@u": resolve("util"),
    "@connect":resolve("connect"),
    "@store":resolve("store")
  }),
  addLessLoader({
    javascriptEnabled: true,
    modifyVars: { "@primary-color": "#1DA57A" },
   
  })
);
  • react-app-rewired 1.0 下config-overrides.js的配置:
const { injectBabelPlugin } = require('react-app-rewired');
const PATH = require('path')
function resolve(url) {
    return PATH.resolve(__dirname, 'src/', url)
}
module.exports = function override(config, dev) {
   
    config = injectBabelPlugin(['import', { libraryName: 'antd-mobile', style: 'css' }], config);

    // 配置别名
    config.resolve.alias = {
        ...config.resolve.alias,
        '@': resolve(''),
        '@as': resolve('assets'),
        '@c': resolve('components'),
        '@commons': resolve('components/commons'),
        '@pages': resolve('pages'),
        '@lib': resolve('lib'),
        '@hoc': resolve('components/hoc'),
        "@store": resolve('store'),
        "@connect": resolve('connect'),
    }
    console.log(config.resolve.alias)

    return config
}

5.json-server 引入

  • my-app 创建 mock 文件夹,创建 db.json,routes.js 文件


    image.png
  • package.json 更改为:
  "scripts": {
    "start": "react-app-rewired start",
    "build": "react-app-rewired build",
    "test": "react-app-rewired test",
    "eject": "rreact-app-rewired eject",
    "mock": "./node_modules/.bin/json-server --routes ./mock/routes.json ./mock/db.json -p 3003"
  },
  • 运行
npm run mock
npm start

6.proxy设置

第一种
  • package.json 文件添加
"proxy": "http://localhost:4000",
第二种
  • 在src目录下创建setupProxy.js
  • npm install http-proxy-middleware --save


    image.png

相关文章

网友评论

      本文标题:react项目搭建

      本文链接:https://www.haomeiwen.com/subject/wrveoqtx.html