主頁 > 企業開發 > 采用React撰寫小程式的Remax框架的編譯流程決議

采用React撰寫小程式的Remax框架的編譯流程決議

2021-04-22 06:36:09 企業開發

Remax是螞蟻開源的一個用React來開發小程式的框架,采用運行時無語法限制的方案,整體研究下來主要分為三大部分:運行時原理、模板渲染原理、編譯流程;看了下現有大部分文章主要集中在Reamx的運行時和模板渲染原理上,而對整個React代碼編譯為小程式的流程介紹目前還沒有看到,本文即是來補充這個空白,   關于模板渲染原理看這篇文章:https://juejin.cn/post/6844904131157557262 關于remax運行時原理看這篇文章:https://juejin.cn/post/6881597846307635214#heading-22 https://zhuanlan.zhihu.com/p/83324871 關于React自定義渲染器看這篇文章:https://juejin.cn/post/6844903753242378248     Remax的基本結構: 1、remax-runtime 運行時,提供自定義渲染器、宿主組件的包裝、以及由React組件到小程式的App、Page、Component的配置生成器
// 自定義渲染器
export { default as render } from './render';
// 由app.js到小程式App構造器的配置處理
export { default as createAppConfig } from './createAppConfig';
// 由React到小程式Page頁面構造器的一系列適配處理
export { default as createPageConfig } from './createPageConfig';
// 由React組件到小程式自定義組件Component構造器的一系列適配處理
export { default as createComponentConfig } from './createComponentConfig';
// 
export { default as createNativeComponent } from './createNativeComponent';
// 生成宿主組件,比如小程式原生提供的View、Button、Canvas等
export { default as createHostComponent } from './createHostComponent';
export { createPortal } from './ReactPortal';
export { RuntimeOptions, PluginDriver } from '@remax/framework-shared';
export * from './hooks';

import { ReactReconcilerInst } from './render';
export const unstable_batchedUpdates = ReactReconcilerInst.batchedUpdates;

export default {
  unstable_batchedUpdates,
};

 

  2、remax-wechat 小程式相關配接器 template模板相關,與模板相關的處理原則及原理可以看這個https://juejin.cn/post/6844904131157557262 templates // 與渲染相關的模板 src/api 適配與微信小程式相關的各種全域api,有的進行了promisify化
import { promisify } from '@remax/framework-shared';

declare const wx: WechatMiniprogram.Wx;

export const canIUse = wx.canIUse;
export const base64ToArrayBuffer = wx.base64ToArrayBuffer;
export const arrayBufferToBase64 = wx.arrayBufferToBase64;
export const getSystemInfoSync = wx.getSystemInfoSync;
export const getSystemInfo = promisify(wx.getSystemInfo);
src/types/config.ts 與小程式的Page、App相關配置內容的適配處理
/** 頁面組態檔 */
// reference: https://developers.weixin.qq.com/miniprogram/dev/reference/configuration/page.html
export interface PageConfig {
  /**
   * 默認值:#000000
   * 導航欄背景顏色,如 #000000
   */
  navigationBarBackgroundColor?: string;
  /**
   * 默認值:white
   * 導航欄標題顏色,僅支持 black / white
   */
  navigationBarTextStyle?: 'black' | 'white';
  
  /** 全域組態檔 */
// reference: https://developers.weixin.qq.com/miniprogram/dev/reference/configuration/app.html
export interface AppConfig {
  /**
   * 頁面路徑串列
   */
  pages: string[];
  /**
   * 全域的默認視窗表現
   */
  window?: {
    /**
     * 默認值:#000000
     * 導航欄背景顏色,如 #000000
     */
    navigationBarBackgroundColor?: string;
    /**
     * 默認值: white
     * 導航欄標題顏色,僅支持 black / white
     */
    navigationBarTextStyle?: 'white' | 'black';

 

src/types/component.ts 微信內置組件相關的公共屬性、事件等屬性適配
import * as React from 'react';

/** 微信內置組件公共屬性 */
// reference: https://developers.weixin.qq.com/miniprogram/dev/framework/view/component.html
export interface BaseProps {
  /** 自定義屬性: 組件上觸發的事件時,會發送給事件處理函式 */
  readonly dataset?: DOMStringMap;
  /** 組件的唯一標示: 保持整個頁面唯一 */
  id?: string;
  /** 組件的樣式類: 在對應的 WXSS 中定義的樣式類 */
  className?: string;
  /** 組件的行內樣式: 可以動態設定的行內樣式 */
  style?: React.CSSProperties;
  /** 組件是否顯示: 所有組件默認顯示 */
  hidden?: boolean;
  /** 影片物件: 由`wx.createAnimation`創建 */
  animation?: Array<Record<string, any>>;

  // reference: https://developers.weixin.qq.com/miniprogram/dev/framework/view/wxml/event.html
  /** 點擊時觸發 */
  onTap?: (event: TouchEvent) => void;
  /** 點擊時觸發 */
  onClick?: (event: TouchEvent) => void;
  /** 手指觸摸動作開始 */
  onTouchStart?: (event: TouchEvent) => void;

 

src/hostComponents 針對微信小程式宿主組件的包裝和適配;node.ts是將小程式相關屬性適配到React的規范
export const alias = {
  id: 'id',
  className: 'class',
  style: 'style',
  animation: 'animation',
  src: 'src',
  loop: 'loop',
  controls: 'controls',
  poster: 'poster',
  name: 'name',
  author: 'author',
  one rror: 'binderror',
  onPlay: 'bindplay',
  onPause: 'bindpause',
  onTimeUpdate: 'bindtimeupdate',
  onEnded: 'bindended',
};

export const props = Object.values(alias);

 

各種組件也是利用createHostComponent生成
import * as React from 'react';
import { createHostComponent } from '@remax/runtime';

// 微信已不再維護
export const Audio: React.ComponentType = createHostComponent('audio');

 

createHostComponent生成React的Element
import * as React from 'react';
import { RuntimeOptions } from '@remax/framework-shared';

export default function createHostComponent<P = any>(name: string, component?: React.ComponentType<P>) {
  if (component) {
    return component;
  }

  const Component = React.forwardRef((props, ref: React.Ref<any>) => {
    const { children = [] } = props;
    let element = React.createElement(name, { ...props, ref }, children);
    element = RuntimeOptions.get('pluginDriver').onCreateHostComponentElement(element) as React.DOMElement<any, any>;
    return element;
  });
  return RuntimeOptions.get('pluginDriver').onCreateHostComponent(Component);
}

 

  3、remax-macro 按照官方描述是基于babel-plugin-macros的宏;所謂宏是在編譯時進行字串的靜態替換,而Javascript沒有編譯程序,babel實作宏的方式是在將代碼編譯為ast樹之后,對ast語法樹進行操作來替換原本的代碼,詳細文章可以看這里https://zhuanlan.zhihu.com/p/64346538; remax這里是利用macro來進行一些宏的替換,比如useAppEvent和usePageEvent等,替換為從remax/runtime中進行引入
import { createMacro } from 'babel-plugin-macros';


import createHostComponentMacro from './createHostComponent';
import requirePluginComponentMacro from './requirePluginComponent';
import requirePluginMacro from './requirePlugin';
import usePageEventMacro from './usePageEvent';
import useAppEventMacro from './useAppEvent';

function remax({ references, state }: { references: { [name: string]: NodePath[] }; state: any }) {
  references.createHostComponent?.forEach(path => createHostComponentMacro(path, state));

  references.requirePluginComponent?.forEach(path => requirePluginComponentMacro(path, state));

  references.requirePlugin?.forEach(path => requirePluginMacro(path));

  const importer = slash(state.file.opts.filename);

  Store.appEvents.delete(importer);
  Store.pageEvents.delete(importer);

  references.useAppEvent?.forEach(path => useAppEventMacro(path, state));

  references.usePageEvent?.forEach(path => usePageEventMacro(path, state));
}

export declare function createHostComponent<P = any>(
  name: string,
  props: Array<string | [string, string]>
): React.ComponentType<P>;

export declare function requirePluginComponent<P = any>(pluginName: string): React.ComponentType<P>;

export declare function requirePlugin<P = any>(pluginName: string): P;

export declare function usePageEvent(eventName: PageEventName, callback: (...params: any[]) => any): void;

export declare function useAppEvent(eventName: AppEventName, callback: (...params: any[]) => any): void;

export default createMacro(remax);
import * as t from '@babel/types';
import { slash } from '@remax/shared';
import { NodePath } from '@babel/traverse';
import Store from '@remax/build-store';
import insertImportDeclaration from './utils/insertImportDeclaration';

const PACKAGE_NAME = '@remax/runtime';
const FUNCTION_NAME = 'useAppEvent';

function getArguments(callExpression: NodePath<t.CallExpression>, importer: string) {
  const args = callExpression.node.arguments;
  const eventName = args[0] as t.StringLiteral;
  const callback = args[1];

  Store.appEvents.set(importer, Store.appEvents.get(importer)?.add(eventName.value) ?? new Set([eventName.value]));

  return [eventName, callback];
}

export default function useAppEvent(path: NodePath, state: any) {
  const program = state.file.path;
  const importer = slash(state.file.opts.filename);
  const functionName = insertImportDeclaration(program, FUNCTION_NAME, PACKAGE_NAME);
  const callExpression = path.findParent(p => t.isCallExpression(p)) as NodePath<t.CallExpression>;
  const [eventName, callback] = getArguments(callExpression, importer);

  callExpression.replaceWith(t.callExpression(t.identifier(functionName), [eventName, callback]));
}
個人感覺這個設計有些過于復雜,可能跟remax的設計有關,在remax/runtime中,useAppEvent實際從remax-framework-shared中匯出; 不過也倒是讓我學到了一種對代碼修改的處理方式,   4、remax-cli remax的腳手架,整個remax工程,生成到小程式的編譯流程也是在這里處理, 先來看一下一個作為Page的React檔案是如何與小程式的原生Page構造器關聯起來的, 假設原先頁面代碼是這個樣子,
import * as React from 'react';
import { View, Text, Image } from 'remax/wechat';
import styles from './index.css';

export default () => {
  return (
    <View className={styles.app}>
      <View className={styles.header}>
        <Image
          src="https://gw.alipayobjects.com/mdn/rms_b5fcc5/afts/img/A*OGyZSI087zkAAAAAAAAAAABkARQnAQ"
          className={styles.logo}
          alt="logo"
        />
        <View className={styles.text}>
          編輯 <Text className={styles.path}>src/pages/index/index.js</Text>開始
        </View>
      </View>
    </View>
  );
};
  這部分處理在remax-cli/src/build/entries/PageEntries.ts代碼中,可以看到這里是對原始碼進行了修改,引入了runtime中的createPageConfig函式來對齊React組件與小程式原生Page需要的屬性,同時呼叫原生的Page構造器來實體化頁面,
import * as path from 'path';
import VirtualEntry from './VirtualEntry';

export default class PageEntry extends VirtualEntry {
  outputSource() {
    return `
      import { createPageConfig } from '@remax/runtime';
      import Entry from './${path.basename(this.filename)}';
      Page(createPageConfig(Entry, '${this.name}'));
    `;
  }
}

 

createPageConfig來負責將React組件掛載到remax自定義的渲染容器中,同時對小程式Page的各個生命周期與remax提供的各種hook進行關聯
export default function createPageConfig(Page: React.ComponentType<any>, name: string) {
  const app = getApp() as any;

  const config: any = {
    data: {
      root: {
        children: [],
      },
      modalRoot: {
        children: [],
      },
    },

    wrapperRef: React.createRef<any>(),

    lifecycleCallback: {},

    onl oad(this: any, query: any) {
      const PageWrapper = createPageWrapper(Page, name);
      this.pageId = generatePageId();

      this.lifecycleCallback = {};
      this.data = https://www.cnblogs.com/dojo-lzz/archive/2021/04/21/{ // Page中定義的data實際是remax在記憶體中生成的一顆鏡像樹
        root: {
          children: [],
        },
        modalRoot: {
          children: [],
        },
      };

      this.query = query;
      // 生成自定義渲染器需要定義的容器
      this.container = new Container(this, 'root');
      this.modalContainer = new Container(this, 'modalRoot');
      // 這里生成頁面級別的React組件
      const pageElement = React.createElement(PageWrapper, {
        page: this,
        query,
        modalContainer: this.modalContainer,
        ref: this.wrapperRef,
      });

      if (app && app._mount) {
        this.element = createPortal(pageElement, this.container, this.pageId);
        app._mount(this);
      } else {
          // 呼叫自定義渲染器進行渲染
        this.element = render(pageElement, this.container);
      }
      // 呼叫生命周期中的鉤子函式
      return this.callLifecycle(Lifecycle.load, query);
    },

    onUnload(this: any) {
      this.callLifecycle(Lifecycle.unload);
      this.unloaded = true;
      this.container.clearUpdate();
      app._unmount(this);
    },

 

Container是按照React自定義渲染規范定義的根容器,最終是在applyUpdate方法中呼叫小程式原生的setData方法來更新渲染視圖
applyUpdate() {
  if (this.stopUpdate || this.updateQueue.length === 0) {
    return;
  }

  const startTime = new Date().getTime();

  if (typeof this.context.$spliceData =https://www.cnblogs.com/dojo-lzz/archive/2021/04/21/=='function') {
    let $batchedUpdates = (callback: () => void) => {
      callback();
    };

    if (typeof this.context.$batchedUpdates === 'function') {
      $batchedUpdates = this.context.$batchedUpdates;
    }

    $batchedUpdates(() => {
      this.updateQueue.map((update, index) => {
        let callback = undefined;
        if (index + 1 === this.updateQueue.length) {
          callback = () => {
            nativeEffector.run();
            /* istanbul ignore next */
            if (RuntimeOptions.get('debug')) {
              console.log(`setData => 回呼時間:${new Date().getTime() - startTime}ms`);
            }
          };
        }

        if (update.type === 'splice') {
          this.context.$spliceData(
            {
              [this.normalizeUpdatePath([...update.path, 'children'])]: [
                update.start,
                update.deleteCount,
                ...update.items,
              ],
            },
            callback
          );
        }

        if (update.type === 'set') {
          this.context.setData(
            {
              [this.normalizeUpdatePath([...update.path, update.name])]: update.value,
            },
            callback
          );
        }
      });
    });

    this.updateQueue = [];

    return;
  }

  const updatePayload = this.updateQueue.reduce<{ [key: string]: any }>((acc, update) => {
    if (update.node.isDeleted()) {
      return acc;
    }
    if (update.type === 'splice') {
      acc[this.normalizeUpdatePath([...update.path, 'nodes', update.id.toString()])] = update.items[0] || null;

      if (update.children) {
        acc[this.normalizeUpdatePath([...update.path, 'children'])] = (update.children || []).map(c => c.id);
      }
    } else {
      acc[this.normalizeUpdatePath([...update.path, update.name])] = update.value;
    }
    return acc;
  }, {});
  // 更新渲染視圖
  this.context.setData(updatePayload, () => {
    nativeEffector.run();
    /* istanbul ignore next */
    if (RuntimeOptions.get('debug')) {
      console.log(`setData => 回呼時間:${new Date().getTime() - startTime}ms`, updatePayload);
    }
  });

  this.updateQueue = [];
}

 

而對于容器的更新是在render檔案中的render方法進行的,
function getPublicRootInstance(container: ReactReconciler.FiberRoot) {
  const containerFiber = container.current;
  if (!containerFiber.child) {
    return null;
  }
  return containerFiber.child.stateNode;
}

export default function render(rootElement: React.ReactElement | null, container: Container | AppContainer) {
  // Create a root Container if it doesnt exist
  if (!container._rootContainer) {
    container._rootContainer = ReactReconcilerInst.createContainer(container, false, false);
  }

  ReactReconcilerInst.updateContainer(rootElement, container._rootContainer, null, () => {
    // ignore
  });

  return getPublicRootInstance(container._rootContainer);
}

 

另外這里渲染的組件,其實也是經過了createPageWrapper包裝了一層,主要是為了處理一些forward-ref相關操作, 現在已經把頁面級別的React組件與小程式原生Page關聯起來了, 對于Component的處理與這個類似,可以看remax-cli/src/build/entries/ComponentEntry.ts檔案
import * as path from 'path';
import VirtualEntry from './VirtualEntry';

export default class ComponentEntry extends VirtualEntry {
  outputSource() {
    return `
      import { createComponentConfig } from '@remax/runtime';
      import Entry from './${path.basename(this.filename)}';
      Component(createComponentConfig(Entry));
    `;
  }
}
  那么對于普通的組件,remax會把他們編譯稱為自定義組件,小程式的自定義組件是由json wxml wxss js組成,由React組件到這些檔案的處理程序在remax-cli/src/build/webpack/plugins/ComponentAsset中處理,生成wxml、wxss和js檔案
export default class ComponentAssetPlugin {
  builder: Builder;
  cache: SourceCache = new SourceCache();

  constructor(builder: Builder) {
    this.builder = builder;
  }

  apply(compiler: Compiler) {
    compiler.hooks.emit.tapAsync(PLUGIN_NAME, async (compilation, callback) => {
      const { options, api } = this.builder;
      const meta = api.getMeta();

      const { entries } = this.builder.entryCollection;
      await Promise.all(
        Array.from(entries.values()).map(async component => {
          if (!(component instanceof ComponentEntry)) {
            return Promise.resolve();
          }
          const chunk = compilation.chunks.find(c => {
            return c.name === component.name;
          });
          const modules = [...getModules(chunk), component.filename];

          let templatePromise;
          if (options.turboRenders) {
            // turbo page
            templatePromise = createTurboTemplate(this.builder.api, options, component, modules, meta, compilation);
          } else {
            templatePromise = createTemplate(component, options, meta, compilation, this.cache);
          }

          await Promise.all([
            await templatePromise,
            await createManifest(this.builder, component, compilation, this.cache),
          ]);
        })
      );

      callback();
    });
  }
}
而Page的一系列檔案在remax-cli/src/build/webpack/plugins/PageAsset中進行處理,同時在createMainifest中會分析Page與自定義組件之間的依賴關系,自動生成usingComponents的關聯關系,              

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/278784.html

標籤:其他

上一篇:TypeScript在React專案中的使用總結

下一篇:04.ElementUI原始碼學習:組件封裝、說明檔案的撰寫發布

標籤雲
其他(157675) Python(38076) JavaScript(25376) Java(17977) C(15215) 區塊鏈(8255) C#(7972) AI(7469) 爪哇(7425) MySQL(7132) html(6777) 基礎類(6313) sql(6102) 熊猫(6058) PHP(5869) 数组(5741) R(5409) Linux(5327) 反应(5209) 腳本語言(PerlPython)(5129) 非技術區(4971) Android(4554) 数据框(4311) css(4259) 节点.js(4032) C語言(3288) json(3245) 列表(3129) 扑(3119) C++語言(3117) 安卓(2998) 打字稿(2995) VBA(2789) Java相關(2746) 疑難問題(2699) 细绳(2522) 單片機工控(2479) iOS(2429) ASP.NET(2402) MongoDB(2323) 麻木的(2285) 正则表达式(2254) 字典(2211) 循环(2198) 迅速(2185) 擅长(2169) 镖(2155) 功能(1967) .NET技术(1958) Web開發(1951) python-3.x(1918) HtmlCss(1915) 弹簧靴(1913) C++(1909) xml(1889) PostgreSQL(1872) .NETCore(1853) 谷歌表格(1846) Unity3D(1843) for循环(1842)

熱門瀏覽
  • IEEE1588PTP在數字化變電站時鐘同步方面的應用

    IEEE1588ptp在數字化變電站時鐘同步方面的應用 京準電子科技官微——ahjzsz 一、電力系統時間同步基本概況 隨著對IEC 61850標準研究的不斷深入,國內外學者提出基于IEC61850通信標準體系建設數字化變電站的發展思路。數字化變電站與常規變電站的顯著區別在于程序層傳統的電流/電壓互 ......

    uj5u.com 2020-09-10 03:51:52 more
  • HTTP request smuggling CL.TE

    CL.TE 簡介 前端通過Content-Length處理請求,通過反向代理或者負載均衡將請求轉發到后端,后端Transfer-Encoding優先級較高,以TE處理請求造成安全問題。 檢測 發送如下資料包 POST / HTTP/1.1 Host: ac391f7e1e9af821806e890 ......

    uj5u.com 2020-09-10 03:52:11 more
  • 網路滲透資料大全單——漏洞庫篇

    網路滲透資料大全單——漏洞庫篇漏洞庫 NVD ——美國國家漏洞庫 →http://nvd.nist.gov/。 CERT ——美國國家應急回應中心 →https://www.us-cert.gov/ OSVDB ——開源漏洞庫 →http://osvdb.org Bugtraq ——賽門鐵克 →ht ......

    uj5u.com 2020-09-10 03:52:15 more
  • 京準講述NTP時鐘服務器應用及原理

    京準講述NTP時鐘服務器應用及原理京準講述NTP時鐘服務器應用及原理 安徽京準電子科技官微——ahjzsz 北斗授時原理 授時是指接識訓通過某種方式獲得本地時間與北斗標準時間的鐘差,然后調整本地時鐘使時差控制在一定的精度范圍內。 衛星導航系統通常由三部分組成:導航授時衛星、地面檢測校正維護系統和用戶 ......

    uj5u.com 2020-09-10 03:52:25 more
  • 利用北斗衛星系統設計NTP網路時間服務器

    利用北斗衛星系統設計NTP網路時間服務器 利用北斗衛星系統設計NTP網路時間服務器 安徽京準電子科技官微——ahjzsz 概述 NTP網路時間服務器是一款支持NTP和SNTP網路時間同步協議,高精度、大容量、高品質的高科技時鐘產品。 NTP網路時間服務器設備采用冗余架構設計,高精度時鐘直接來源于北斗 ......

    uj5u.com 2020-09-10 03:52:35 more
  • 詳細解讀電力系統各種對時方式

    詳細解讀電力系統各種對時方式 詳細解讀電力系統各種對時方式 安徽京準電子科技官微——ahjzsz,更多資料請添加VX 衛星同步時鐘是我京準公司開發研制的應用衛星授時時技術的標準時間顯示和發送的裝置,該裝置以M國全球定位系統(GLOBAL POSITIONING SYSTEM,縮寫為GPS)或者我國北 ......

    uj5u.com 2020-09-10 03:52:45 more
  • 如何保證外包團隊接入企業內網安全

    不管企業規模的大小,只要企業想省錢,那么企業的某些服務就一定會采用外包的形式,然而看似美好又經濟的策略,其實也有不好的一面。下面我通過安全的角度來聊聊使用外包團的安全隱患問題。 先看看什么服務會使用外包的,最常見的就是話務/客服這種需要大量重復性、無技術性的服務,或者是一些銷售外包、特殊的職能外包等 ......

    uj5u.com 2020-09-10 03:52:57 more
  • PHP漏洞之【整型數字型SQL注入】

    0x01 什么是SQL注入 SQL是一種注入攻擊,通過前端帶入后端資料庫進行惡意的SQL陳述句查詢。 0x02 SQL整型注入原理 SQL注入一般發生在動態網站URL地址里,當然也會發生在其它地發,如登錄框等等也會存在注入,只要是和資料庫打交道的地方都有可能存在。 如這里http://192.168. ......

    uj5u.com 2020-09-10 03:55:40 more
  • [GXYCTF2019]禁止套娃

    git泄露獲取原始碼 使用GET傳參,引數為exp 經過三層過濾執行 第一層過濾偽協議,第二層過濾帶引數的函式,第三層過濾一些函式 preg_replace('/[a-z,_]+\((?R)?\)/', NULL, $_GET['exp'] (?R)參考當前正則運算式,相當于匹配函式里的引數 因此傳遞 ......

    uj5u.com 2020-09-10 03:56:07 more
  • 等保2.0實施流程

    流程 結論 ......

    uj5u.com 2020-09-10 03:56:16 more
最新发布
  • 使用Django Rest framework搭建Blog

    在前面的Blog例子中我們使用的是GraphQL, 雖然GraphQL的使用處于上升趨勢,但是Rest API還是使用的更廣泛一些. 所以還是決定回到傳統的rest api framework上來, Django rest framework的官網上給了一個很好用的QuickStart, 我參考Qu ......

    uj5u.com 2023-04-20 08:17:54 more
  • 記錄-new Date() 我忍你很久了!

    這里給大家分享我在網上總結出來的一些知識,希望對大家有所幫助 大家平時在開發的時候有沒被new Date()折磨過?就是它的諸多怪異的設定讓你每每用的時候,都可能不小心踩坑。造成程式意外出錯,卻一下子找不到問題出處,那叫一個煩透了…… 下面,我就列舉它的“四宗罪”及應用思考 可惡的四宗罪 1. Sa ......

    uj5u.com 2023-04-20 08:17:47 more
  • 使用Vue.js實作文字跑馬燈效果

    實作文字跑馬燈效果,首先用到 substring()截取 和 setInterval計時器 clearInterval()清除計時器 效果如下: 實作代碼如下: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta ......

    uj5u.com 2023-04-20 08:12:31 more
  • JavaScript 運算子

    JavaScript 運算子/運算子 在 JavaScript 中,有一些運算子可以使代碼更簡潔、易讀和高效。以下是一些常見的運算子: 1、可選鏈運算子(optional chaining operator) ?.是可選鏈運算子(optional chaining operator)。?. 可選鏈操 ......

    uj5u.com 2023-04-20 08:02:25 more
  • CSS—相對單位rem

    一、概述 rem是一個相對長度單位,它的單位長度取決于根標簽html的字體尺寸。rem即root em的意思,中文翻譯為根em。瀏覽器的文本尺寸一般默認為16px,即默認情況下: 1rem = 16px rem布局原理:根據CSS媒體查詢功能,更改根標簽的字體尺寸,實作rem單位隨螢屏尺寸的變化,如 ......

    uj5u.com 2023-04-20 08:02:21 more
  • 我的第一個NPM包:panghu-planebattle-esm(胖虎飛機大戰)使用說明

    好家伙,我的包終于開發完啦 歡迎使用胖虎的飛機大戰包!! 為你的主頁添加色彩 這是一個有趣的網頁小游戲包,使用canvas和js開發 使用ES6模塊化開發 效果圖如下: (覺得圖片太sb的可以自己改) 代碼已開源!! Git: https://gitee.com/tang-and-han-dynas ......

    uj5u.com 2023-04-20 08:01:50 more
  • 如何在 vue3 中使用 jsx/tsx?

    我們都知道,通常情況下我們使用 vue 大多都是用的 SFC(Signle File Component)單檔案組件模式,即一個組件就是一個檔案,但其實 Vue 也是支持使用 JSX 來撰寫組件的。這里不討論 SFC 和 JSX 的好壞,這個仁者見仁智者見智。本篇文章旨在帶領大家快速了解和使用 Vu ......

    uj5u.com 2023-04-20 08:01:37 more
  • 【Vue2.x原始碼系列06】計算屬性computed原理

    本章目標:計算屬性是如何實作的?計算屬性快取原理以及洋蔥模型的應用?在初始化Vue實體時,我們會給每個計算屬性都創建一個對應watcher,我們稱之為計算屬性watcher ......

    uj5u.com 2023-04-20 08:01:31 more
  • http1.1與http2.0

    一、http是什么 通俗來講,http就是計算機通過網路進行通信的規則,是一個基于請求與回應,無狀態的,應用層協議。常用于TCP/IP協議傳輸資料。目前任何終端之間任何一種通信方式都必須按Http協議進行,否則無法連接。tcp(三次握手,四次揮手)。 請求與回應:客戶端請求、服務端回應資料。 無狀態 ......

    uj5u.com 2023-04-20 08:01:10 more
  • http1.1與http2.0

    一、http是什么 通俗來講,http就是計算機通過網路進行通信的規則,是一個基于請求與回應,無狀態的,應用層協議。常用于TCP/IP協議傳輸資料。目前任何終端之間任何一種通信方式都必須按Http協議進行,否則無法連接。tcp(三次握手,四次揮手)。 請求與回應:客戶端請求、服務端回應資料。 無狀態 ......

    uj5u.com 2023-04-20 08:00:32 more