In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces the relevant knowledge of "how the React project goes from Javascript to Typescript". Many people will encounter such a dilemma in the operation of actual cases, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
Start the migration
Before I start the transfer, I would like to say something beside the point. This article only records the problems I encountered in the transfer process and how I solved them, and will not involve the teaching of typescript. So before you read this article, you must have a basic understanding of typescript, otherwise it will be very difficult for you to read.
Environmental adjustment
Because Typescript is a superset of Javascript, many of its syntax browsers are not recognized, so it cannot be run directly on browsers. It needs to be compiled into JavaScript to run on browsers, just as ES6 needs to be compiled by babel to support more earlier browsers.
Tsconfig.json
First of all, we have to install a typescript, which is the same reason that we need to install a babel-core before using babel.
Yarn global add typescript
This command is to install typescript globally, in fact, I personally suggest that it is installed in the project directory, because the typescript version of each project is not exactly the same, and it is easy to cause problems due to different versions. But later I have to execute the tsc command, so I put it in the overall situation. In the case of *, both the global and the project are installed, but if you use the tsc command in the script in package.json, then it is enough to install it in the project. Next, we execute the following command to generate tsconfig.json, which is of the same nature as .babelrc.
Tsc-init
After execution, there will be a tsconfig.json in the root directory of your project, but there will be a lot of comments, so we don't have to worry about it first.
Webpack
Install ts-loader to process ts and tsx files, similar to babel-loader.
Yarn add ts-loader-D
The corresponding webpack needs to be added with ts's loader rules:
Module.exports = {/ / omit part of the code. Module: {rules: [{test:/\ .tsx? $/, loader:'ts-loader'} / / omit some code.]} / /. Omit part of the code}
When using javascript in the past, some people may not use .jsx files, the whole project uses .js files, and webapck doesn't even match the .jsx rules. But if you want to use all .ts files in typescript projects, it won't work, and you'll get an error, so when you use jsx, you still have to use .tsx files, so I've added .tsx rules here.
Delete babel
With regard to babel, many people on the Internet choose to keep it, the reason is very simple, it is to prevent the use of JavaScript in the future, but I personally do not think it is necessary to keep babel. Because we basically only use javascript when we use third-party packages in the whole project, and these third-party packages are basically compiled into es5 code, so there is no need for babel to deal with it. It is even less possible to use javascript in business logic, because it loses the meaning of using typescript. To sum up, I personally think it is necessary to delete things related to babel and reduce the complexity of the project. But there is one exception:.
When you use some babel plug-ins that happen to have features that typescript can't provide, you can keep babel and combine it with typescript.
File name adjustment
All the files at the end of .js under the entire src have to change the file name, and those that use jsx syntax will be changed to .tsx files, and those that are not used will be changed to .ts files. This piece of work is relatively large and will be a headache. In addition, after the change, there will certainly be a lot of red marks in the document, so don't rush to change it. Later, we will classify and unify it.
Solve the error report
Webpack entry file not found
Because we change main.js to main.tsx when we adjust the file name, the entry file of webpack should be changed to main.tsx.
Module.exports = {/ / omit part of the code. Entry: {app:'. / src/main.tsx'}, / / omit part of the code.}
Hint cannot use the syntax of jsx
This solution is very simple, just go to tsconfig to configure it.
{"compilerOptions": {"jsx": "react"}}
The jsx configuration item has three values to choose from, namely "preserve", "react-native" and "react". JSX is reserved in the generated code in preserve and react-native mode for subsequent conversion operations (for example, Babel). In addition, the preserve output file will have a .jsx extension, and react-native is a .js extension. The react schema generates React.createElement, which no longer needs to be converted before using it, and the output file has a .js extension.
Mode input / output output file extension preserve.jsxreactReact.createElement ("div"). Jsreact-native.js
The alias configured in webpack cannot be parsed
Module.exports = {/ / omit part of the code. Resolve: {alias: {'@': path.join (_ _ dirname,'../src')} / / omit part of the code.}, / / omit part of the code.}
We need to do some extra configuration in tsconfig.json here.
{"compilerOptions": {"baseUrl": ".", "paths": {"@ / *": [". / src/*"]}
How to configure, please see the typescript documentation, I will not expand the introduction, but it is important to note that baseUrl and paths must be used together.
Https://www.tslang.cn/docs/ha...
Unable to add extension name automatically, so the corresponding module cannot be found.
We used to configure it like this in webpack:
Module.exports = {/ / omit part of the code. Resolve: {/ / omit part of the code. Extensions: ['.js', '.jsx', '.json']}, / / omit part of the code.}
But all the .js and .jsx files in our project have been changed to .ts and .tsx files, so the configuration needs to be adjusted.
{/ / omit part of the code. Resolve: {/ / omit part of the code. Extensions: ['.ts', '.tsx', '.js', '.jsx', '.json']}, / / omit some code.}
Could not find a declaration file for module'*'
This is relatively simple, it indicates that you can't find the declaration file of which module, you can install which module, the installation format is as follows:
Yarn add @ types/**
For example, if you prompt Could not find a declaration file for module 'react', you should execute the following command:
Yarn add @ types/react
This is limited to third-party packages. If the project's own module prompt lacks a declaration file, you will need to write the corresponding declaration file yourself. For example, if you mount an object on the global object window, you need to make a declaration if you need to use it, otherwise an error will be reported. As for how to write it, it depends on the typescript documentation, so I won't explain it here.
Https://www.tslang.cn/docs/ha...
Cannot find type definition file for'*'
These are not directly used in our business code, but are used by third-party packages. In this case, you need to check whether the configuration item typeRoots in tsconfig.json is misconfigured. Generally speaking, you don't need to configure typeRoots, but if you need to add an additional declaration file path, you need to modify it. TypeRoots has a default value, and some people mistakenly think that the default value is "[" node_modules "]", so someone will configure it like this:
{"compilerOptions": {"typeRoots": ["node_modules",..., ". / src/types"]}}
In fact, the default value of typeRoots is "[" @ types "]", and all visible "@ types" packages are loaded during editing, such as ". / node_modules/@types/", ".. / node_modules/@types/", ".. /.. / node_modules/@types/" and so on. So when you encounter this problem, your configuration should be changed to:
{"compilerOptions": {"typeRoots": ["@ types",..., ". / src/types"]}}
In a real project, @ types basically exists under node_modules in the root directory, so here you can change it like this:
{"compilerOptions": {"typeRoots": ["node_modules/@types",..., ". / src/types"]}}
Decorators (decorator) is not supported
Typescript turns off the experimental ES decorator by default, so you need to turn it on in tsconfig.json.
{"compilerOptions": {"experimentalDecorators": true}}
Module'* 'has no default export
Prompt module code does not contain "export"
Default ", but you use the default import form of" import from ". For this problem, we need to set the tsconfig.json configuration item" allowSyntheticDefaultImports "to true. Default import is allowed from modules that do not have a default export. But don't worry about the impact on the code, this is just for type checking.
{"compilerOptions": {"allowSyntheticDefaultImports": true}}
Of course, you can also use the configuration item "esModuleInterop" and set it to true. According to the default value of "allowSyntheticDefaultImports", it is as follows:
Module = = "system" or-- esModuleInterop
There are two main functions of the configuration item "esModuleInterop":
Provide _ _ importStar and _ _ importDefault helper to be compatible with babel ecology
Turn on allowSyntheticDefaultImports
For the choice of "esModuleInterop" and "allowSyntheticDefaultImports", if you need typescript combined with babel, there is no doubt that you choose "esModuleInterop". Otherwise, you are used to choosing "allowSyntheticDefaultImports" and prefer to use whatever you like. Of course, "esModuleInterop" is the safest option, and if you're not sure about it, use "esModuleInterop" obediently.
Global objects such as document and window are not recognized
In this case, we need to add a dom library to the configuration item lib in tsconfig.json, as follows:
{"compilerOptions": {"lib": ["dom",..., "esNext"]}}
The problem of marking red in documents
With regard to this problem, we need to consider it in two cases, * * is .ts files, and the second is .tsx files. Let's take a look at the specific points of attention (Ps: the points mentioned below do not completely solve the problem of red marks in the file, but they can solve most of the problems of red marks):
* species: .ts file
This kind of file is relatively few in your project, it is easier to deal with, according to the actual situation to add a type limit, there is no special need to talk about.
The second kind: .tsx file
This situation is all react components, and react components are divided into stateless components and stateful components, so let's look at them separately.
Stateless component
For stateless components, first restrict it to be a FunctionComponent (functional component), and then restrict its props type. For example:
Import React, {FunctionComponent, ReactElement} from 'react'; import {LoadingComponentProps} from' react-loadable'; import'. / style.scss'; interface LoadingProps extends LoadingComponentProps {loading:boolean, children?:ReactElement} const Loading:FunctionComponent = ({loading=true,children}) = > {return (loading?: children)} export default Loading
If you think the name FunctionComponent is too long, you can choose to use the type alias "SFC" or "FC".
Stateful component
For stateful components, there are three main points to note:
Hongmeng official Strategic Cooperation to build HarmonyOS Technology Community
Both props and state have type restrictions
State uses readonly to restrict the operation of "this.state=**"
Type restrictions on event objects
Import React, {MouseEvent} from "react" Interface TeachersProps {user:User} interface TeachersState {pageNo:number, pageSize:number, total:number, teacherList: {id: number, name: string, age: number, sex: number, tel: string, email: string} []} export default class Teachers extends React.PureComponent {readonly state = {pageNo:1, pageSize:20, total:0 UserList: []} handleClick= (e:MouseEvent) = > {console.log (e.target) } / /... Omit part of the code render () {return Click me}}
In a real project, the state of a component may have many values, and it will be troublesome to write it in the way we did above, so consider the following simple way to write it:
Import React, {MouseEvent} from "react"; interface TeachersProps {user:User} const initialState = {pageNo:1, pageSize:20, total:0, teacherList: []} type TeachersState = Readonly export default class Teachers extends React.PureComponent {readonly state = initialState handleClick= (e:MouseEvent) = > {console.log (e.target);} / /. Omit part of the code render () {return Click me}}
This way of writing will be a lot easier to write code, but the effect of type restriction is obviously not as good as *, so this method is only for reference and can be selected according to the actual situation.
Ant Design lost style file
When we start the project, some students may lose the style on their pages, as follows:
When we open the console, we find that the corresponding style cannot be found in the class name of Ant Design:
This happens because after we removed babel, the babel plug-in babel-plugin-import, which is used to load component style files on demand, is also lost. However, the typescript community has a Typescript version of babel-plugin-import called "ts-import-plugin". Let's install it first:
Yarn add ts-import-plugin-D
This plug-in needs to be used in conjunction with ts-loader, so the following adjustments need to be made in webpack configuration:
Const tsImportPluginFactory = require ('ts-import-plugin') module.exports = {/ / omit some code. Module: {rules: [{test: /\ .tsx? $/, loader: "ts-loader", options: {transpileOnly: true / / (optional) getCustomTransformers: () = > ({before: [tsImportPluginFactory ({libraryDirectory: 'es', libraryName:' antd') Style: true})})}}]} / omit part of the code.}
Here we should pay attention to the configuration of transpileOnly: true, which is an optional configuration. I suggest that this configuration is added only in large projects, and small projects are not necessary. Because typescript's semantic checker checks all files each time it is compiled, it takes a long time to compile when the project is large. The easiest way to solve this problem is to turn off the semantic checking of typescript with the configuration transpileOnly: true, but at the cost of losing type checking and the export of declaration files, so it is not recommended to add this configuration unless you want to improve compilation efficiency in large projects.
After the configuration is complete, your browser console may report an error similar to the following:
This occurs because the module parameter in your typescript configuration file tsconfig.json is not set correctly. Two situations can cause this problem:
Module is set to "commonjs"
Target sets "ES5" but does not set module (when target is not "ES6", module defaults to "commonjs")
The solution is to set module to "esNext" to solve the problem.
{"compilerOptions": {"module": "esNext"}}
Some guys may say that it is OK to set it to "ES6" or "ES2015". As for why I choose "esNext" instead of "ES6" or "ES2015", the main reason is that after it is set to "ES6" or "ES2015", it cannot be dynamically imported, because the project uses the react-loadable package, and if it is set to "ES6" or "ES2015", it will report the following error:
Typescript prompts us to set it to "commonjs" or "ESNext" before it can be imported dynamically, so just to be on the safe side, I suggest you set it to ESNext. When it is finished, our page can be displayed normally.
When it comes to the module parameter, I'd like to mention the moduleResolution parameter, which determines how typescript handles the module. When we set module to "esNext", we can ignore the parameter moduleResolution, but if we set it to "ES6" in our project, we need to set it. Take a look at the moduleResolution default rules first:
Module = "AMD" or "System" or "ES6"? "Classic": "Node"
When our module is set to "ES6", moduleResolution defaults to "Classic" and what we need is "Node". Why choose "node", mainly because node module parsing rules are more in line with our requirements, parsing speed will be faster, as for the details of the introduction, you can refer to the Typescript documentation.
This is the end of the introduction of "how the React Project goes from Javascript to Typescript". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.