• Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

preface

  • As a developer, you are bound to encounter various technical problems during the development process, especially when using a new technology. This article documents some thoughts and problems I have encountered recently, including some elementary mistakes that should be avoided.

A circular reference

  • What is the difference between CommonJS and ES6 modularity?
  • In the moduleAInside reference moduleB, again in the moduleBReferenced in theABecause ofES ModuleIs run at compile time, so circular references can cause program exceptions. Such as:
// A.js import { bname } from './B.js'; Console. log('A Module, bname=', bname); export const aname = 'A'; // B.js import { aname } from './A.js'; Console. log('B Module, aname=', aname); export const bname = 'B';Copy the code

The code performance

  • To achieve the same function, different writing performance is certainly not the same.

case1: Return early

  • For example, when we need to find whether a value is in an object of an array, we will iterate. There are many ways to iterate, such as:ForEach, map, for, for... Of, for... inAnd so on.
  • for, for… in,for… What’s the difference between “of” and “forEach” and “map”?
List. ForEach (item => {if(item.key === target){//... }}) const len = list.length for(let I = 0; i < len; i ++) { if(item.key === target){ // ... break; }}Copy the code

Example 2: There is a faster way

  • The nativeDomI’m sure you’re all familiar with itdocument.addEventListenerdocument.querySelector...And so on. The addition ofAPIThere are more powerful features, but for certain conditions, we should choose the faster oneAPI.
/ / the function more complete, more document. QuerySelector document. QuerySelectorAll... / / document. The faster the getElementById document. GetElementsByClassName...Copy the code

None Example Clear all files in the specified path and domain namecookie

  • When we need to save the login for other sitescookie, we need to save to the specified path, when not used to clear the correspondingcookie.
  • Set up thecookieIf the value is expired, the browser will automatically clear itcookie.
const clearCookie = (path = '/', domain = document.domain) => { const keys = document.cookie.match(/[^ =;] + (? ==)/g); const overdueTime = new Date(0).toUTCString(); if (keys) { const len = keys.length; for (let i = 0; i < len; i++) { document.cookie = `${keys[i]}=0; path=${path}; expires=${overdueTime}`; Cookie = '${keys[I]}=0; path=${path}; domain=${document.domain}; expires=${overdueTime}`; Cookie = '${keys[I]}=0; path=${path}; domain=${domain}; expires=${overdueTime}`; }}};Copy the code

The NPM package cannot be installed

  • NPM and YARN Common operations guide

Public package

  • Normally we install packages fromnpmOfficial mirror source (Registry.npmjs.org/), but due to some packages…
/ / 1. Switching taobao image source NPM config set registry https://registry.npm.taobao.org / / 2. Use CNPM // 3. Enable flip wall/proxyCopy the code

Private package

  • This is used when we need to install some privately distributed packages (such as internally packaged packages)yarnIf a message indicating that the installation fails is displayed.
// 1. Modify yarn.lock. Check whether the successful installation person submits the yarn.lock file, modify the file configuration of the corresponding package, and reinstall the yarn.lock file. NPM config set registry NPM config set registryCopy the code

ChromeDebug the mobile terminalh5

  • Use Chrome://inspect to debug webViews on Android devices
  • Note:
    1. You need your phone to open oneh5Page;
    2. Mobile phones and computers together with a network;
    3. AppInside cannot debug find native (Android, iOS,Developer) to see if the corresponding package has a problem;
    4. Go into the white screen, turn on the wall/proxy.

React Nativerelated

  • Recently doReact NativeSome problems encountered in the development of.

AppReturn interception did not take effect

  • Debugging interceptorAppWhen triggering a return operation, do notAppHome debugging,AppThe home page will triggerAppExit function.

ChromedebuggingVSReal machine commissioning

  • I haven’t done it beforeReact NativeI don’t have a good understanding of how it works, which leads to a problem (judging the phone’s system).
  • I developed it locally for useChromeDebug in the browser, so I’m usingwindow.navigator.userAgentTo judge, there are no problems with debugging.
export function isAndroid_ios() { let u = window.navigator.userAgent let isiOS = !! u.match(/\(i[^;] +; ( U;) ? CPU. Mac OS X + /) / / ios terminal let isIOS1 = u.i ndexOf (' iPhone ') > 1 | | u.i ndexOf (' ios) > 1 return isiOS | | isIOS1? 'ios' : 'android' }Copy the code
  • When I released it, the function failed to work on my mobile phone. After continuous investigation, I found the reason that the function failed to work on my mobile phonewindow.navigator.userAgent. In order to useReact NativeIn thePlatformAnd through itOSAttribute to judge.
// use import {Platform} from 'react-native'; Platform.OS === 'ios' ? 'ios' : 'other'; // export const Platform: | PlatformIOSStatic | PlatformAndroidStatic | PlatformWindowsOSStatic | PlatformMacOSStatic | PlatformWebStatic; Interface PlatformIOSStatic extends PlatformStatic {constants: PlatformConstants & { forceTouchAvailable: boolean; interfaceIdiom: string; osVersion: string; systemName: string; }; OS: 'ios'; isPad: boolean; isTVOS: boolean; Version: string; }Copy the code
  • The reason is that both are usedJavaScriptThe engine is different. When inChromeWhen remote debugging is used in, it almost runs in a browserRNApplication (then useV8 JavaScript Engine) and throughWebSocketsCommunicates with the simulator (or device). It will be used if run without remote debugging enabledJavaScript Core. There are many differences between these environments that can lead to inconsistencies, so don’t just rely on enablementJSDebug to run the application, which may give you error errors or hide errors that actually cause problems on the actual device.
  • JavaScriptCore learning JavaScriptCore

Screen display direction setting

  • Use the react – native – orientation
  • The corresponding readme. md file is also introduced in more detail than I believe.

Gets the width and height of the screen

  • throughreact-native-orientationIn theaddOrientationListenerMethod to listen for screen orientation changes, perform the following fetch function.
import { Dimensions } from 'react-native'; // Dimensions. Get ('screen'). Height * all with bangs (including safe zone and full screen mode) // Get ('REAL_WINDOW_HEIGHT') export function getCurrentScreen(mode: 'window' | 'screen' = 'screen') { const width = Dimensions.get(mode).width; const height = Dimensions.get(mode).height; return [width, height]; }Copy the code

AppForeground and background running status

  • React Native AppState
// React Native import { AppState } from 'react-native'; const _handleAppStateChange = (nextAppState) => { if (nextAppState ! = = null) {if (nextAppState = = = 'active') {/ / / / at the front desk... } else if (nextAppState === 'background') { }}} / / Web document. AddEventListener (" visibilitychange ", () = > {the if (document. Hidden) {/ / / / the background... } else {// foreground //... }});Copy the code

Past wonderful

  • Doesn’t the front end know Nginx yet? Come and learn
  • VS Code’s guide to improving development efficiency, quality, and coding experience
  • Gold nine front-end interview summary!
  • Build from 0 Vite + Vue3 + element-plus + VUE-Router + ESLint + husky + Lint-staged
  • “Front-end advanced” JavaScript handwriting methods/use tips self-check
  • Public account open small program best solution (Vue)
  • Axios you probably don’t know how to use

“Likes, favorites and comments”

❤️ follow + like + comment + share ❤️, lingering fragrance in hand, thank 🙏 everyone.