Write in front:
- Create-react-app is referred to as CRA
- In this paper, YARD is used for package installation, project startup and packaging. Students who prefer NPM can change to NPM command by themselves
- This project has realized the basic project framework built based on CRA2.x, and realized a page imitating Tencent Weather
- The basic framework of this paper can be used to build enterprise-level background management system
- The author built the environment macOS Mojave10.14.1, node version 8.12.0, IDE is VSCode
- The Node environment is required. You need to search for the Node environment, which is not covered in this document
- If you are new to CRA or React, make sure to clone the source code on GitHub
- This project aims to record the framework building process of CRA2. X enterprise-level project. Incidentally, I wrote a page imitating Tencent Weather in my spare time, mainly for the practical use of antD, MOBx and Echarts-for-React, which are three important libraries
- All the links in this article are marked “required” or “optional”. For those with basic knowledge, please clone the code on GitHub and learn from the article (again!).
- GitHub address of this project
- The main bug of the DEMO project is the server. Because the weather forecast system uses IP positioning, I used proxy configuration proxy in the development stage, there is no problem, but when it is mounted to the Nginx server, it is located to Beijing by default every time through IP positioning. I have consulted a lot of information. There is a solution, but it requires backend coordination, but my backend is a third party API, this problem feels a bit unsolvable… If there is a solution to the students or other exchange ideas of the students, welcome to give me issues, or give me a message, we communicate)
- Because the third-party API has access traffic limits, if the access is excessive, the page may not be opened. If the demo cannot be opened, please contact the author in time
1. Start the ROAD to CRA (Learn step)
Create-react-app is the basic scaffolding tool used in the preparation of the project. You can check the Github CRA link to see how to use scaffolding: NPX create-react-app my-app CD my-app make sure the project runs ok YARN start Open custom webpack configuration YARN eject or NPM run eject This operation is irreversible. The significance of this operation is that we can modify the Webpack configuration, global variables and other configurations, which is necessary for an enterprise development framework
2. Cross-env and global variable configuration (Learn step)
(1) Cross-env is used to solve the problem of unified MAC and Windows project operation. In most cases, it is used under Windows platform similar to: NODE_ENV=production command line directives get stuck. Cross-env can be used for different platforms without worrying about cross-platform issues. Cross-env yarn add cross-env –dev package.json
Note: Once cross-env is installed, you just need to prefix each command linecross-env
Build :production” build:test” and “build:production” are used to run the development environment. Cross-env has a lot of parameters, which I’ll explain in more details below
Configure the global variable file
My project distinguishes three global variables, including. Env.development.env.test.env.production, which are used to represent the development environment, test environment package, and formal environment package respectively
-
The configuration global variables file must be named as.env.xxx and placed in the root directory of the project. The common ones are development, test, and production.
-
File Format: In “.env.xxxx”, XXX can be used to specify the desired name, but it is usually the same as the above three names. Now let’s go back to package.json, which is the “cross-env configuration screenshot” above. RECORD_ENV= XXXXX (* * * * * * * * * * * * * * * * * * * * * * * * * * * * *) Next, modify the env.js file in the config folder in the root directory, which contains the code to read the global file
Const NODE_ENV = process.env.node_env; Const NODE_ENV = process.env.xxxx; Where XXXX is the context-specific parameter we use for each command run in package.json scripts, I used RECORD_ENV
-
Variable naming format in global variable files: the format must be “REACT_APP_XXX”. The global variable files in different environments are named by their own global variables. After writing the required variables in each file, we have completed the configuration of global variables
Special Note 1: On the second cross – env and global variable configuration, this step is not necessary infrastructure operation, because in general personal project doesn’t exist many environment, environment variables of different issues, but for enterprise project framework structures, this configuration is necessary, because the backend will exist test environment, the difference between the development environment
Special Note 2: Notes on built-in environment variables: We’ve changed the configuration of env.js. If you’re careful, you’ll notice that NODE_ENV is everywhere. Here’s a quick description of create-react-app’s built-in environment variables: PUBLIC_URL and NODE_ENV PUBLIC_URL is the publication path of static resources and is used in public/index.html. The default value is “”, which needs to be configured. NODE_ENV has three values as follows: NPM start => development NPM test => test NPM run build => production NODE_ENV cannot be overwritten manually, so we need to manually set a new environment variable name, Then, when scripts runs the command, specify the current environment variable file by specifying environment parameters, which is what we did in the “Modify env.js file configuration” screenshot above
3. Configure ESLint and prettier (Elementary steps)
Significance: this section is to configure the code standard of team development, as an enterprise the front end of the project structure, team development is indispensable, but if you think there is no need for students, also can skip this section, the code specification testing and configuration, and is not necessary to run configuration
First, we need to install prettier, yarn add prettier –dev
Prettier is a common tool for formatting code. The IDE used by the author is VSCode, which has the default formatting specification but is not as useful as prettier. You can also install prettier in VSCode’s plug-in library
As for ESLint, the default configuration of our CRA framework has been pre-installed with ESLint. We just need to choose the rules we want to use. Here I choose the standard code format specification of Airbnb, which is commonly used in the industry. Do not repeat here, readers can search for comparison
Install yarn add eslint-config-airbnb –dev Airbnb is our main code inspection rule for prettier install yarn add eslint-config-airbnb –dev prettier –dev Prettier: dev eslint-config-prettier: dev EsLint -config-prettier: dev EsLint -config-prettier: dev EsLint -config-prettier: dev esLint -config-prettier: dev esLint -config-prettier: dev esLint -config-prettier: dev esLint -config-prettier: dev esLint -config-prettier Eslint-plugin-prettier causes ESLint to call Prettier to check your code style
ESLint –init can create configuration files step by step according to the wizard, or directly create several configuration file formats in the root directory, I usually use.eslintrc.json, here I only describe my configuration file
Json is stored in the root directory to mask unwanted ESLint rules. Eslintignore is used to mask folders that do not need esLint detection, such as node_modules, webpack configuration files, etc. These folders do not need ESLint detection
Finally, for IDE users, all ides now have plugins for ESLint and prettier, which rely on the node_modules source code libraries. Plugins are just a way for ides to integrate the two libraries. Then restart the IDE
At this point, the configuration of the ESLint and Prettier plugins is complete
Special note: Forbidden rules: Because Airbnb is a strict specification, but there are still many rules, in actual development, there will be a lot of trouble, I shield the following rules, the specific meaning of the rules can be referred to the relevant document “prettier/prettier”: “error”, “import/no-unresolved”: 0, “react/forbid-prop-types”: 0, “prefer-destructuring”: 0
4. Install LoDash (Elementary steps)
** Description: ** If you are not familiar with LoDash, you can skip this step. Lodash is a JS library that is commonly used in the industry. It contains a very comprehensive encapsulation method, but in fact, most people can use the built-in JS methods to meet their needs. So I personally prefer to use LoDash clean and direct, so install yarn Add LoDash
5. Install less related, webpack configuration less support (Elementary steps)
Meaning Description: This section is to add less support to the project. In actual development, we usually use less style as shown in the following figure. Readers who are not familiar with less can learn less by themselves. The configuration of SASS is for readers to study by themselves. Here we only talk about the configuration of LESS
The less module supports YARN add less –dev yarn add less-loader –dev
Then respectively in the root directory of the config/webpack config. Dev. Js and config/webpack config. Prod. Js file configuration
The config/webpack config. Dev. Js file
-
Step 1 Modification
Pay attention to: Many relevant documents do not
javascriptEnabled: true
This code, because less in 3 x version and above, will need to add this sentence, otherwise an error, unless installed less3. X versions of the following -
Step 2 Modify
Pay attention toNode_modules does not require CSS modularity to be enabled, as shown in the map “Less used in the project”.
include: [/node_modules/]
, and then deal with the local developed code, need to add CSS modular configuration, otherwise can not be usedimport styles from 'xxxx'
Add less to local lessexclude: [cssModuleRegex, /node_modules/]
CssModuleRegex is the default configuration for cra2. x, so leave it alone
The config/webpack config. Prod. Js file Said this file package when running webpack configuration, and the config/webpack config. Dev. Js is slightly different, but adding support for less this configuration, is exactly the same configuration, I won’t go into it here
Install antD, configure antD on demand, install mobx mobx-react, modify Babel configuration (Learn step)
Meaning Description: This section is to add antD framework, mobx mobx-React, and add load on demand configuration. About this content, there is a more detailed introduction on antD website, readers can also refer to antD website. In addition, this step will explain in detail that cra2. x has been preinstalled with babel7. There are a lot of different configurations, Install ANTdyarn add ANTd Install ANTD Load required components as required yarn add babel-plugin-import –dev Install mobxyarn add mobx Install mobx-reactyarn add mobx-react
The default Babel configuration of CRA is placed in package.json. In this case, I removed the Babel configuration from package.json and created a separate
Add [“import”, {“libraryName”: “antd”, “style”: true}] to your plugins.
Add support for ES7 decorators syntax as shown in the figure above, add [“@babel/plugin-proposal-decorators”, {“legacy”: True}], modifiers are the simplest and most intuitive mobx usage, and it is recommended that any framework using Mobx use modifiers
Yarn add transform-decorators-legacy –dev, dev, dev, dev, dev, dev Then add the transform-decorators-Legacy configuration to your plugins, but cra2. x has raised Babel to 7. If you are still using the old configuration method, Babel 7 has been installed on CRA2. X. The ‘decorators’ plugin requires a’ decoratorsBeforeExport ‘option, whose value must be a boolean. If you are migrating from Babylon/Babel 6 or want to use the old decorators proposal, You should use the ‘decorators-legacy’ plugin instead of ‘decorators’ github.com/mobxjs/mobx…
As mentioned above, there may be articles in the CRA1. X version that require NPM I transform-decorators-Legacy to support the use of decorators, but the CRA2. X framework is not needed because CRA2. Babel7 support for decorators has been changed to @babel/plugin-proposal-decorators, and the configuration has been changed to this configuration [“@babel/plugin-proposal-decorators”, {“legacy”: Yarn add babel-react-app, this is a preset package for CRA. This is a preset package. Yarn add babel-react-app, this is a preset package for CRA. It contains a number of possible plugin packages that CRA installed when you created your project, including the @babel/plugin-proposal-decorators support package that we need to add to.babelrc. Presets [“react-app”], presets use babel-react-app, presets are preset
This library already covers a very comprehensive Babel configuration plug-in, This library presets common ones such as @babel/preset-env (for each version of Babel conversion) @babel/plugin-proposal-class-properties (for class syntax) The @babel/plugin-transform-runtime and so on are already wrapped in, so the only support we need to add here is the configuration of modifiers
Then some readers may wonder why we are adding this sentence to plugins since babel-preset-react-app already includes @babel/plugin-proposal-decorators that we need to use, Because there is a line in the babel-react-app source code that must be passed in “typescript: True “for @babel/plugin-proposal-decorators to start. It is possible for typescript projects to add “presets” to Babel: [[“react-app”,{typescript:true}]] will enable the package supported by the decorator, but I’ve already tried it and still get an error when running the project. [“@babel/plugin-proposal-decorators”, {“legacy”: true}] True, which is supported by the older version of the modifier, and the newer version of the modifier library does not support mobx usage, so if you do not add “Legacy “: true, you will still get an error.
DecoratorsBeforeExport: decoratorsBeforeExport: decoratorsBeforeExport: decoratorsBeforeExport: decoratorsBeforeExport: decoratorsBeforeExport: decoratorsBeforeExport: decoratorsBeforeExport: decoratorsBeforeExport: But the official also collected the suggestion in the community will have decoratorsBeforeExport: true or decoratorsBeforeExport: false, so at this stage the classmate of everyone only need to use legacy: true, The argument for true or false is an argument between two formats. If you are interested, you can see the link for a detailed discussion of this parameter
7. React-router4.x use and route load on demand (Learn step)
Installation of yarn add react – the router – dom react – dom is based on the react – the router, the router – it was little more than the react – the router dom class components, such as the component, Install react-router-dom directly for browser development
Router4.x (router4.x, Router4.x, Router4.x, Router4.x, Router4.x, Router4.x, Router4.x
The index JSX file
App. JSX file
Routers. JSX file
On-demand loaded (key, routing on demand loading is front must step of optimization, on-demand loaded, as the name implies, the page is loaded when only request the current routing the resources required, and not all routing resource to the request, if you don’t configure on-demand loaded, in large projects, after the late will affect the user experience very much)
Load on demand configuration article, there are many on the Internet, here I only introduce two, is my personal feel more lightweight simple two methods, methods more than these two, the reader can search, understand the principle in detail
- Install react-loadable (a support library loaded on demand)
yarn add react-loadable
useimport Loadable from 'react-loadable';
const MineItem = Loadable({ loader: () => import('./pages/mine'), loading: MyLoadingComponent });
Screenshots:
- Custom bundle. js component, routing component with this Bundle in the outer screenshots:
8. Install axios (Learn step)
Meaning Description: Axios and FETCH are two API request libraries commonly used in the industry, both of which have been used by the author. In general, AXIOS is simpler and lighter. For specific usage and comparison, please consider the basic use of installing YARN Add AXIos and check the Axios Chinese document. I’ll just mention one configuration that I used in my project, which is axios’ interception configuration. Axios can intercept requests, return data, and do some processing ahead of time, such as:
Once you have configured the Axios interceptor, you can import the interceptor file directly into index.js
9. Chart Library (Elementary steps)
Meaning Description: Enterprise projects, it is impossible not to use the visual icon library, here as a personal learning, can not need to install, but the author’s framework to achieve a copy of Tencent weather page, using echarts-for-react, this reader according to the need, Determine whether to install YARN add echarts-for-react
Echarts-for-react is an API that uses echarts-for-React as a component, and is used as an API that uses echarts-for-React as a component. Echarts-for-react is the only echarts API that can be used with d3 and echarts.
10. Cross-domain proxy configuration for the front-end development environment (Learn step)
Meaning Description: Cross domain is one of the basic skills necessary each front-end engineer, for cross-domain I don’t do more introduced, cross-domain enterprise projects are mostly used in CORS cross-domain method, is the main configuration on the server, and the author introduced here is a front cross domain method, individual events such as the author, and use the third-party API, I can’t change the server Settings, so I use the front-end proxy method, configuration method is very simple
Just add “proxy”: “http://xxxxxx” to package.json. XXXX is the address of the proxy server
One more thing: When I was building a project using CRA1.x, proxy could have been configured like this
11. Nginx preparation (Elementary steps)
Significance: this section is belongs to the category of the server over, I was not prepared to introduce in detail in this article, my next article, introduces the correct steps I nginx server over and hit the pit, listed below are some of the things need to be configured, interested readers can find information online learning system: Nginx reverse proxy setup (using a third-party API, you must configure nginx reverse proxy, otherwise the API will not access anything, if you write your own backend, you can configure the use of CORS cross-domain. Nginx gzip compression configuration (greatly increased page loading speed, enabling Gzip reduced my application from 15s to 4.x seconds) Can greatly speed up page loading)
Write in the back
The author of imitation of tencent weather page implementation of major bugs in server, because the weather forecast system, use the IP position, my agent in development using the proxy configuration, there is no problem, but mount to nginx server, every time the default via IP positioning, positioning to Beijing, I looked at a lot of information, There is a solution, but it requires backend coordination, but my backend is a third party API, this problem feels a bit unsolvable… If there is a solution to the students or other exchange ideas of the students, welcome to give me issues, or give me a message, we exchange growth together
Articles in the end, if there is any false or misleading, please contact the author immediately, this is the first time the author frame structures, the nature of the guidance document, the hard to avoid omissions and obscure places (or the things I write too much the authors own understanding, let the reader more confused 😓 😓 😓 😓), please forgive me a lot.