(Turn) react building project

Original: https://segmentfault.com/a/1190000016342792

EDITORIAL

Every time the project will build react to configure a lot of things, over time will forget how configuration. In order to facilitate their memories but also to other developers to quickly develop react when building applications, pretending this record.

This project is based on  create-react-app  the scaffolding configuration. The main configuration of a number of projects to develop methods commonly used, such as webpack the  sass , redux , 热加载 , 代理 and the introduction of other tools library and so on.

Initialize the project

First of all, you must first use create-react-app react to create a project, refer to  https: //github.com/facebookin ...

installation create-react-app

npm install -g create-react-app

Create an application

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

Note: my-app refers to the name of the project, users can customize the project name

This time can be entered on the command line

npm start : Start the project will be able to see the project start page.

image description

npm run build : Project released.

Such a project would react simple initialization is completed.

However, by default all configuration is hidden, to custom configuration, you need to run a command: npm run eject
this time will prompt, the command irreversible, whether to continue, type y, so that all configuration items you are out. Will generate a configfolder, this time you can also do some customized configured.

Project Configuration

Compatible with IE

The introduction of element-react UI framework will complain ReferenceError: “Symbol”未定义

  • solution:

Project introduction babel-polyfill, you can import in the app.js

Configuration webpack

Based on some of the configuration webpack

Configuration sass

Scaffolding default is not configured sass, sass if a project needs to be configured separately

1, mounted reliance  npm install --save-d node-sass sass-loader
2, the following modifications config webpack.config.dev.jsand webpack.config.prod.js, need to be modified, the development environment and publishing environments are separate configuration.

Modify cssloader
be test: /\.css$/, modified as:  test: /\.(css|scss|sass)$/,i.e. identifying scss / sass file

Finally, add
sass-loader

image description

Configuring an Alias

Alias ​​facilitate our rapid introduction in the project file. For example, we have a project in the public directory for the file src / util / tools, such as the following file structure

├── src                                   
│   ├── assets                            # 项目资源
│   │   └── ...
│   ├── containers                        # 页面容器
│   │   └── pages
│   │       └── pageA                     # 页面A     
│   │           └───a.js                  # a.js │   │── utils # 其他工具类 │   │ └── tools │   ├── index.js # webpack打包入口文件 

Deep inside the hierarchy of components a.jsneed to introduce toolsfile, we'll use ../../../util/toolsto find the relative location of the file, but after using the alias webpack configuration can be located directly to the /srcdirectory.

// 未使用别名
import tools from '../../../util/tools';

// 使用别名后 import tools from '@/util/tools'; // '@/' 指向 'src/'

Configuration

dev and prod environment need to be configured

Configured in the resolve / alias

Which  resolve is a custom function.

function resolve(dir) {
    return path.join(__dirname, '..', dir) }

It can also be written as

'@': path.join(__dirname, '..', 'src')

image description

Configuration thermal load

create-react-appThe project has the configuration of a thermal load, we only need to import documents in the project index.jsenabled the heat load on the line, added directly to the end

// index.js
/* 热加载 */
if (module.hot) {
  module.hot.accept(); }

image description

Configure a proxy server

Request interface cross-domain problem often encountered, there are many ways of cross-domain, the configuration is most webpack dev_server, but this method is not valid in the application create-react-app generated in the front end of the development, for this application should proxy at the package.json

// package.json
"proxy": "http://api.enjoycut.com/"

// 或者
"proxy": { "/article": { "target": "http://api.enjoycut.com/", "changeOrigin": true, "secure": false } } // 下面的方式没有配置过

Configuring Routing

react-router4 of use and previous versions use different router

react-router4 document address

Configuration redux

Configuration  @connectdecorator

Redux in the project can be accessed directly by way @connect

Not Configured
image description

After configuration

image description

Incidentally, here the decorator, the module needs to be installedbabel-plugin-transform-decorators-legacy

Then arranged inside package.jsonplugins

image description

Other items in the configuration tool

classnames

In switching className react troublesome, may be used trinocular simple operation, but more complex, class more trouble, such as the slightly more complex dynamic switching div plurality className, recommend a tool library that provides simple switching className .

clsssnames use the document

image description

      <div className={classNames('clip_item', {
      'clip_active': isActive, 
      'effect_hover': activeDrag === 'video_inner',
       'dragging': is_dragging} )}> // 默认classNAme: 'clip_item' // isActive === true 则添加className 'clip_active' // is_dragging === true 则添加className 'dragging'

moment

Formatting time in the project tool library, the time format to any format you want! Very convenient.

moment().format('MMMM Do YYYY, h:mm:ss a'); // 九月 10日 2018, 7:04:30 晚上
moment().format('dddd'); // 星期一 moment().format("MMM Do YY"); // 9月 10日 18 moment().format('YYYY [escaped] YYYY'); // 2018 escaped 2018 moment().format(); // 2018-09-10T19:04:30+08:00

moment.js文档地址:http://momentjs.cn/


项目后期优化

antd按需加载

一般情况下,我们按照antd官网使用方式在css中导入整个ui的样式,@import '~antd/dist/antd.css';
比如我们在项目中只使用了Button,和Table,但是这样实际上加载了全部的 antd 组件的样式(对前端性能是个隐患);
因此我们需要使用按需加载,只加载我们使用过得组件样式。

注意:如果是运行了eject ,webpack配置了babelrc: false ,单独根目录新建.babelrc会报错的,需要在webpack.dev.js配置,在module模块 ,loader: require.resolve('babel-loader')对象中的plugins数组中添加

这里只展示允许eject暴露了webpack配置文件的配置方式,未暴露webpack配置方式请参考https://segmentfault.com/a/11...

  1. 安装babel-plugin-import

    npm install --save-dev babel-plugin-import

  2. 给 webpack 的 babel-loader plugins 加上 babel-plugin-import

需要修改两个文件 /config/webpack.config.prod.js 和 /config/webpack.config.dev.js (修改的内容一样,升级后的create-react-app合并为一个文件 webpack.config.js)找到加载 babel-loader 的地方,往他的 plugins 加入如下代码

[
    require.resolve('babel-plugin-import'),// 导入 import 插件
    {
      libraryName: 'antd',   //暴露antd style: 'css' } ] 

最后形成的配置如下(create-react-app 版本不同最后的配置可能不一样,原理一样):

   // Process application JS with Babel.
    // The preset includes JSX, Flow, TypeScript, and some ESnext features.
    {
      test: /\.(js|mjs|jsx|ts|tsx)$/,
      include: paths.appSrc, loader: require.resolve('babel-loader'), options: { customize: require.resolve( 'babel-preset-react-app/webpack-overrides' ), plugins: [ [ require.resolve('babel-plugin-named-asset-import'), { loaderMap: { svg: { ReactComponent: '@svgr/webpack?-svgo,+ref![path]', }, }, }, ], // antd按需加载 [ require.resolve('babel-plugin-import'),// 导入 import 插件 { libraryName: 'antd', //暴露antd style: 'css' } ], ], // This is a feature of `babel-loader` for webpack (not Babel itself). // It enables caching results in ./node_modules/.cache/babel-loader/ // directory for faster rebuilds. cacheDirectory: true, cacheCompression: isEnvProduction, compact: isEnvProduction, }, },

代码分隔(react-loadable)

一个动态导入加载组件的高阶组件.

未使用前

import Home from'./Home';

使用后

import loadable from '@/utils/loadable'
const Home = loadable(() => import('./Home '));

loadable组件

import React from 'react';
import Loadable from 'react-loadable'; //通用的过场组件 const loadingComponent =()=>{ return ( <div></div> ) }; //过场组件默认采用通用的,若传入了loading,则采用传入的过场组件 export default (loader,loading = loadingComponent)=>{ return Loadable({ loader, loading }); }

参考链接

Pre-rendered configuration (Prerender SPA Plugin)

Construction html file generated phase pre-rendered matching path (Note: Each requires a pre-rendered route has a corresponding html). Html file has been constructed out of parts.

If you use both in the project 代码分隔and 预加载will lead to a page splash screen. The reason is preloaded package will be loaded out of html, rendering static pages, and then request the page after the code js separated. Html will lead to the root node to mount again. It is not recommended to use the pre-loaded while using separate codes.

Configuration

1.npm install prerender-spa-plugin

2. Locate the  /config/webpack.config.prod.jsfile

const path = require('path')
const PrerenderSPAPlugin = require('prerender-spa-plugin') module.exports = { plugins: [ ... new PrerenderSPAPlugin({ // Required - The path to the webpack-outputted app to prerender. staticDir: path.join(__dirname, '../build'), // Required - Routes to render. routes: ['/home', '/convert', '/trim', '/merge', '/watermark', '/remove', '/download'], }) ] } 

3. To add routes are added to the routes which, at the same time need to change the back-end configuration ngnix

/ -> home/index.html
/home -> home/index.html
/convert -> convert/index.html
/trim -> trim/index.html /merge -> merge/index.html /watermark -> watermark/index.html /remove -> remove/index.html /download -> download/index.html 除了上面的路径,其他路径全部指向 index.html 

Single Page Application multi-route pre-rendered guide  https://juejin.im/post/59d49d976fb9a00a571d651d
instructions  https://github.com/chrisvfritz/prerender-spa-plugin


Source

To facilitate the rapid construction projects, according to the present embodiment are arranged in all the code github project.
https: //github.com/zhaosheng8 ...

Guess you like

Origin www.cnblogs.com/liujiacai/p/11202095.html