Poking fun at a few words

One of typescript’s biggest selling points for me is the joy of type checking and IDE hints. I used to resist using TS because I felt it was too much to add and learn new things, but now IT seems that TS is the trend, and my favorite framework vue is going to be refactoring in TS.

After I developed a project using RN, I couldn’t wait to get involved in TS in the next project, but it was difficult at the beginning and I encountered many problems, mainly in configuration… I have tried to solve the problem by myself, but I feel it is not perfect. I hope I can be guided by the TS leader of nuggets. Besides, I have seen the react-Native pit in the last project, which is not normal.

start

Typescript-react-native Starter: Typescript-React-native Starter: Typescript-React-native Starter: Typescript-React-native Starter: Typescript-React-native Starter

After I finished, there were two problems that I solved temporarily

NO1:

React-native has a global global object, similar to Windows on the Web. Sometimes I want to put a global method or variable on the global object. How do I do that?

Error:(25, 3) TS2304: Cannot find name ‘global’. wfk? I clicked @types/react-native/index.d.ts

. declare global { function require(name: string): any; }...Copy the code

I have been dealing with this problem for a long time. At the beginning, I went to Github to search for issues, thinking it was a bug. Therefore, I raised a issue on Github, hoping for a response, but I need to find a solution: Create a new folder in your SRC directory, typings, to put your own type declaration files. Create a new global.d.ts folder, name it whatever you want, and write the following code inside

declare module global{
	let name:string;
	let time:Time;
	let dp:(px:number)=>number;
	let font:(px:number)=>number;
}
Copy the code

And then you can use it in your code. Look at the picture

Github isseus received a reply while I was writing this article

Reply is

It isn’t a good practice to use this global keyword, but it exists and should be present in react-native context. Well, it’s not a best practice, but sometimes it’s really necessary just like the Window object, sometimes it’s necessary to hang things on it, and then we can see in the source code that they add global

That depends on when they release the new code, but it’s learning. Another question I said in the source code is used

declare global{ function require(name: string): any; /** * Console polyfill * @see https://facebook.github.io/react-native/docs/javascript-environment.html#polyfills */ interface Console { error(message? : any, ... optionalParams: any[]): void; info(message? : any, ... optionalParams: any[]): void; log(message? : any, ... optionalParams: any[]): void; warn(message? : any, ... optionalParams: any[]): void; trace(message? : any, ... optionalParams: any[]): void; debug(message? : any, ... optionalParams: any[]): void; table(... data: any[]): void; disableYellowBox: boolean; ignoredYellowBox: string[]; }}Copy the code

What does it mean to declare global directly? Declare namespace, Declare Module, Declare function, etc

NO2:

This is what I saw in the Microsoft tutorial


// styles

const styles = StyleSheet.create({
  root: {
    alignItems: "center",
    alignSelf: "center"
  }
})
Copy the code

Um, perfect, no problem, but I wrote my own error report

// styles
const styles = StyleSheet.create({
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 0,
  }
});
Copy the code
Error:(42, 11) TS2322: Type 'RegisteredStyle<{ fontSize: number; textAlign: string; margin: number; }>' is not assignable to type 'StyleProp<TextStyle>'. Type 'RegisteredStyle<{ fontSize: number; textAlign: string; margin: number; }>' is not assignable to type 'RecursiveArray<false | TextStyle | RegisteredStyle<TextStyle>>'. Property 'length' is missing in type 'Number & { __registeredStyleBrand: { fontSize: number; textAlign: string; margin: number; }; } '.Copy the code

It means the wrong type, the solution

Type Style={welcome:TextStyle}// Define an alias // styles const styles = StyleSheet. Create <Style>({welcome: {fontSize: 20, textAlign: 'center', margin: 0, } });Copy the code

However, it is very troublesome to write this, and I refer to the article others did not pass in the type here, later checked github seems someone said that this is a new version of the problem, so I do not know how to solve this problem, I will write this first, I want to define a global Style alias or interface? Just use it for each page as I did in global.d.ts

import {ViewStyle} from "react-native";

interface Style{
	[prop:string]:ViewStyle
}
Copy the code

“Global” is a variable that cannot be identified. “global” is a variable that cannot be identified. “Global” is a variable that cannot be identified. I really need some help explaining this.

NO3:

How to write path alias? I did a search on Baidu and, well, there is babel-plugin-root-import, and there are two problems to solve

  1. Resolve ts identification path alias problem
  2. Ts is recognized at compile time and has to be recognized at run time by Babel to convert the alias

Following this idea, I have both configured, but I can’t get Babel to recognize them, always reporting an error that the module configuration can’t be found, something like this

// .babelrc
{

  "env": {
    "production": {
      "plugins": [
        "transform-remove-console",[
          "babel-plugin-root-import",
          {
            "paths":[
              {
                "rootPathSuffix": "src",
                "rootPathPrefix": "@src"
              },
              {
                "rootPathSuffix": "./src/components",
                "rootPathPrefix": "@components"
              }
            ]
          }
        ]
      ]
    }
  },
  "presets": ["module:metro-react-native-babel-preset"],
  "plugins": [[
    "babel-plugin-root-import",
    {
      "paths":[
        {
          "rootPathSuffix": "src",
          "rootPathPrefix": "@src"
        },
        {
          "rootPathSuffix": "./src/components",
          "rootPathPrefix": "@components"
        }
      ]
    }
  ]]
}

Copy the code

I feel that this configuration is correct, according to the plug-in document written exactly the same, but still not, am I wrong? But eventually I gave up, Because my latest version of React-Native already uses a tool called react-native typescript- Transformer to convert TS to JS at compile time. It used to be said that to write RN in TS, you had to convert THE TS compiler to JS first and then let Rn read the converted code. The development experience is very bad ah, now with this, don’t have to go alone on js, but I think it is a bad, is it only convert ts do not check type error, also is the wrong type so you can run, about this lot also have a discussion, I probably have seen, seemingly means to intentionally, I still hope to direct an error, don’t run. Now I have to resort to the IDE hints. To get back to that, I found a note in the documentation of the tool

Json file in the folder you want to alias, and write a name attribute in it to call the alias you configured. This alias should be the same as the tsconfig alias. For example, I configured a path alias in tsconfig

"BaseUrl" : ". ", / / must pay attention to this configuration, or paths useless "paths" : {" @ components / * ": / SRC/components / *"},Copy the code

Next I’ll create a new package.json in the Components folder

{
  "name":"@components"
}
Copy the code

This way, finally running, and ts can recognize, the amazing is ws can jump, before configuring the alias in vUE, WS does not know anything else

The last

I will keep updating this article and hope that some of you can comment on the above issues. In addition, after contacting React-Native, I deeply feel the strong github issues and the need for English ability. I encountered rn pit most I just need to put the error in rn issues a search can be found, but all are English, so programmers really need to improve English reading ability oh, finally say, rn new version do not immediately use, 100% pit, if the ability to step on the pit, in addition to the problem, do not be afraid, Mention issues, with youdao dictionary translation can roughly say it, several of my problems are to mention issues to solve the last. Emmm, it’s late at night. Good night!