Recently, the company gathered all react projects into TS to explain some problems encountered in the work. React +typescript — antd
I. Construction project
npx create-react-app my-demo -typescript
Copy the code
The project created looks like this:
npm run eject
Copy the code
The folder that appears in the project is Config. It contains the webpack configuration items. Next, we execute
npm run start
Copy the code
When the project is running, open a web page at http://localhost:3000 in your browser.
Integrate WITH ESLint
My advice is that eslint is a validation tool, so if you can install it on vscode, try to install it on vscode. There is a plugin called eslint on vscode. You can open vscode and install it as shown below.
npx eslint --init
Copy the code
After executing the command, there will be a file in the project called eslintrc.json, where we can configure the validation project in the rules file.
Inherit stylelint
Eslint is a validation tool for js and ts. We also need to install the CSS stylelint validation tool, which can also be downloaded from vscode
npm install stylelint-config-recommended -g
Copy the code
After installing the stylelint-config-recommended directory, go to node’s Global resources and follow the configuration below. Note that if you don’t know where the global resource is, just look at the node environment variable configuration item and go to XXXX\nodejs\node_global\node_modules\. So go into vscode Settings as shown
4. Path alias Settings
During development, the titans of big companies hate hard coding, especially when paths are dot-dot-dot, so alias Settings are very important. In the React js project, you only need to configure the alisa configuration in webpack.config.js, but in the TS project, you also need to configure the tsconfig.json. The details are shown in webpack.config.js
Resolve :{// Some other configurationalias: {The '@'Paths. appSrc is the SRC path. Please refer to config/paths.js} for details.Copy the code
In the tsconfig. Json
"compilerOptions"{// Here are some other configurations that already exist // Here are the configurations that need to be added"baseUrl": "src"."paths": {
"@ / *": [
". / *"]}}Copy the code
The path to use
import { someComponent } from '@/components/User';
Copy the code
Note: Be sure to change baseUrl to SRC in tsconfig. Otherwise the configuration is still unsuccessful.
5. The CSS is modular
Json, which means that the sass-loader is integrated in the scaffolding by default. If we were using less, we would install it as follows.
npm insatll less less-loader -D
Copy the code
Go to config/webpack.config.js and find the sass config file. We will add our own config file after sass and just change the name and copy it
const sassRegex = /\.(scss|sass)$/; / / the original file const sassModuleRegex = / \. The module \. (SCSS | sass) $/; Const lessRegex = /\.less$/; // Add file const LessLessmoduleregex = /\.module\.less$/; // Add a fileCopy the code
Sass = less; sass = less; sass = less; sass = less
Load antD style files as needed
When we introduce ANTD globally, not all files and styles need to be used. If only one component is used but all styles are loaded, will it cause excessive loading and affect performance? We need to configure it in package.json to load on demand.
"babel": {// Some existing configurations // Add the following configurations"plugins": [["import",
{
"libraryName": "antd"."style": "css"}}]]Copy the code
Basic types of components
If a file returns JSX, the extension is TSX. If the file does not return JSX, the extension is ts. The files used to define types end in.d.ts. In TS, TSX data are all need to define the type, I will give you some basic types:
State scenario, using Redux inside the componentexport interface IMdState {
[k: string]: any;
}
const mapStateToProps = (state: IMdState) => ({
loading: actions.fetchList(state),
});
Copy the code
import React from 'react'
import Slider from '@/components/slider/slider'
functionMock Data Const bannerList = [1, 2, 3, 4]. Map () => {return { imageUrl: "http://p1.music.126.net/ZYLJ2oZn74yUz5x8NBGkVA==/109951164331219056.jpg"}});return <div>
<Slider bannerList={bannerList} />
</div>
}
export default React.memo(Recommend)
Copy the code
You can refer to: blog.csdn.net/weixin_4390… I recommend that all variables in ts files should have a type, and avoid using any. The result of any is the same as that of js without a type, so please write a specific type.
Differences between TS files and.d.ts files
.ts means that your code is written in TS.
However, the code in.ts will eventually be compiled into.js js code for others to use. At this point, the type information is lost. How to do? Therefore, the ts compiler automatically generates external.d.ts files based on the information in.ts, and uses them with the generated JS files. Js files are for the browser engine to read, while.d.ts files are for the IDE. For reference when writing code.
On the other hand, if your code is not written in TS and you just want to give it to someone else with type information, then you will need to write the.d.ts file by hand.
HTTP cross-domain request
When we debug the interface, the data in the background is from the specific server, not localhost, and their IP is different, which violates the same origin policy of the browser, and the console will report an error, as shown in the figure:
At this point we can either use HTTP cross-domain requests or webPack reverse proxies. Cross-domain request is a manipulation on the code, which I do not recommend, because when you go online, resources may be put together, there will be no cross-domain, so you write in the code of cross-domain will be very bad, can not be online when you change the past one by one, how stupid! The following two methods are recommended:
1 Reverse Proxy
If all you need for the reverse proxy is an address, you can configure it directly in package.json
"proxy": "http://api02.aliyun.venuscn.com"
Copy the code
There are multiple addresses that need proxies, so we can only install @types/ HTTP-proxy-middleware.
Note: In typescript, all dependencies need to be prefixed with @types/ otherwise they cannot be imported.
npm install @types/http-proxy-middleware -S
Copy the code
Create a file setupproxy.js under SRC
// setupproxy.js const proxy = require(// setupproxy.js //'http-proxy-middleware');
module.exports = function(app) {
app.use(proxy(
'/province',
{
target: 'http://api02.aliyun.venuscn.com',
changeOrigin: true,
secure: false,
pathRewrite: {
'^/province': '/',}})); app.use(proxy('/poetry',
{
target: 'http://jisutssbs.market.alicloudapi.com',
changeOrigin: true,
secure: false,
pathRewrite: {
'^/poetry': '/',}})); };Copy the code
Request data in a service
axios.get('/province/area/all? level=0'); / / this request for: http://api02.aliyun.venuscn.com/area/all?level=0 axios. Get ('/poetry/tangshi/search? Keyword = no '); / / this request for: http://jisutssbs.market.alicloudapi.com/tangshi/search?keyword=Copy the code
If you ask why configure a file to reverse proxy? Open the config file of your project and find paths.js. You will find it already configured for you. Just add the configuration file and go ahead.
2. HTTP packet capture tool Fiddler
If you are lazy like me, I will directly recommend you to use this tool, the specific usage in my file has related agent method, please check. The idea was that the code would do everything and fiddler would manage the requests. There are also some configuration instructions, next time to update! Thank you very much!