jsDoc 전도

Mary-Kate Olsen
풀어 주다: 2024-10-28 06:22:02
원래의
847명이 탐색했습니다.

TLDR;

레거시 코드 기반으로 작업하세요. 우리 중 많은 사람들이 시간이 지나면서 피할 수 없습니다. Typescript 대신 jsDoc을 사용해 보도록 안내합니다. 그 놀라운 진실을 밝혀야 합니다!

먼저 정리하자: jsDoc 또는 TS는 개발자 시간을 의미합니다(나중에 검토 포함, 재사용, 모든 환경에서 해당 코드 보기: git 웹 페이지, 임의 편집기, 크롬, 파이어폭스 등). ..:devtool, vim, cat ... );

첫 번째 악장

편집기를 열고 jsDoc이 작동하는지 테스트하기 위한 적절한 설명을 작성하세요.

/** @typedef { 'JS' | 'JQuery' | 'TS' | 'jsDoc' } Phase; */

/**
 * On typing ' editor will popup string list.
 *
 * @type {Phase}
 */
const badCase = 'React'; // !!!! lint alert !!!!

/** @type {Phase} */
const goodCase = 'JQuery';
로그인 후 복사
로그인 후 복사

jsDoc과 Typescript 비교

제 경험상 TS 코드를 대체할 수 있는 jsDoc이 있는데, 보너스로 이 둘 사이에 웜홀이 존재합니다.

jsDoc의 가장 큰 기능 imho: 이는 표준 JS 주석 시스템을 사용하므로 JS 코드를 손상시키지 마십시오. 이 코드는 JS가 실행 가능한 모든 곳에서 실행됩니다.

feature jsDoc Typescript
compiling freedom Do not need compiling the code. mandatory to compile
dependency freedom Can working without any dependency at least TS is your dependency
namespace freedom Don't interfere Types and other imports names. You can use same name of component and component Type in React for example. Typesript names are identical including as any other referenct
rework freedom Don't need to change existing code, just insert a comment. at least some part in your code need to be turn to TS
legacy freedom Can be use even transform to Typescript the project is not option. Many legacy projects affected this situation. need to push management to allow that modification
Maximalism freedom Don't need to use every where. Even you can use on a new commits, and after easy to search which is the new or reworked parts. also enough to turn build system, and just part of code to TS
future freedom Later can easy trasnlate to TS. Under the hood this is use same technic, just different way. need to work if decide to use JS instead TS
mindset freedom Because this is a comment your know well this is don't made any type check at runtime for you as TS also. TS is noising your code

jsDoc 편집자 경험

어떤 편집기에서든 jsDoc을 작성할 수 있지만 이해하는 경우는 거의 없습니다.

노드 모듈 경험

저는 npm 모듈인 jsdoc-duck도 만들었습니다. jsDoc 코딩 모듈입니다. 이는 TypeScript 없이는 jsDoc npm 모듈을 생성할 수 없다는 점을 강조했습니다. 아마도 vite 구축 매개변수를 파악하는 데 더 많은 시간을 투자한다면 올바른 솔루션을 찾을 수 있을 것입니다. 그러나 좋은 소식은 npm과 함께 해당 모듈을 사용하지 않고 대신 우리 코드를 빌려오는 것입니다. index.js를 한 위치에 복사하면 프로그램에 새 종속성을 삽입하는 데 사용되며 아무 일도 일어나지 않습니다. 모듈 소유자가 모듈을 다른 것으로 바꾸면.

jsDoc 사이의 웜홀 타이프스크립트

Typescript와 jsDoc이 서로 호환된다는 좋은 소식은 단지 jsDoc이 약간 다른 구문을 사용한다는 것입니다. 그러나 typescript에서 jsDoc 모듈 유형을 사용할 수 있으며 javascript/js jsDoc 프로그램에서도 typescript 모듈 유형을 사용할 수 있습니다. 따라서 최종 결정은 귀하의 손에 달려 있습니다.

노란 벽돌길을 따라가세요

VS 코드 예제는 jsDoc 코드에서 유형이 얼마나 잘 보이는지 보여줍니다. 제 생각에는 이것이 코드에 주는 노이즈가 놀라울 정도로 적습니다.

jsDoc Evangelism

보너스

:: VS 코드 조각

/** @typedef { 'JS' | 'JQuery' | 'TS' | 'jsDoc' } Phase; */

/**
 * On typing ' editor will popup string list.
 *
 * @type {Phase}
 */
const badCase = 'React'; // !!!! lint alert !!!!

/** @type {Phase} */
const goodCase = 'JQuery';
로그인 후 복사
로그인 후 복사

:: jsdoc-duck 코드

( 이 보기에서 구문 강조 표시는 유형을 이해하는 데 도움이 되지 않습니다). 하지만 이 짧은 프로그램은 jsDoc이 TS 고급 기능도 사용할 수 있는 좋은 예입니다.

  "@type": {
    "prefix": ["ty"],
    "body": ["/** @type {<pre class="brush:php;toolbar:false">import { useMemo, useReducer } from "react";

/**
 * @template T - Payload Type
 * @typedef {T extends { type: infer U, payload?: infer P } ? { type: U, payload?: P } : never} ActionType
 */

/** @template AM - Actions Map @typedef {{ [K in AM['type']]: K }} Labels */

/** @template AM - Actions Map @typedef {{ [T in AM["type"]]: Extract<AM, { type: T }> extends { payload: infer P } ? (payload: P) => void : () => void }} Quack */

/**
 * @template ST - State
 * @template AM - Actions Map
 * @typedef {(state: ST, action: AM) => ST} Reducer
 */

/**
 * Factory function to create a typed action map.
 * @template AM - Actions Map
 * @param {Labels<AM>} labelsObject - The keys representing action labels.
 * @param {function} dispatch - The dispatch function for actions.
 * @return {Quack<AM>} The resulting typed action map.
 */
export const quackFactory = (labelsObject, dispatch) => Object
  .keys(labelsObject)
  .reduce(
    /**
     * @arg {Quack<AM>} acc
     * @arg {keyof Labels<AM>} type
     * @return {Quack<AM>}
     */
    (acc, type) => ({
    ...acc,
    [type]: (payload) => {dispatch({ type, payload });}
  }), {});

/**
 * A factory hook to create a state and a typed dispatch functions\
 * @exports useDuck
 * @template AM - Actions Map
 * @template ST - State Typer
 * @param {(st: ST, action: AM) => ST} reducer - The reducer function to manage the state.
 * @param {ST} initialState - The initial state value.
 * @return {[ST, Quack<AM>]} The current state and a map of action dispatch functions.
 */
export const useDuck = (reducer, initialState, labels) => {
  const [state, dispatch] = useReducer(reducer, initialState);
  const quack = useMemo(
    () => quackFactory(labels, dispatch),
    [dispatch, labels]
  );
  return ([state, quack]);
};
로그인 후 복사
} */"], "description": "jsdoc type" }, "@typedef": { "prefix": ["td"], "body": ["/** @typedef {} Foo */"], "description": "jsdoc typedef" },

코딩을 즐기세요. 대신 종속성을 추가하세요

위 내용은 jsDoc 전도의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

원천:dev.to
본 웹사이트의 성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
저자별 최신 기사
인기 튜토리얼
더>
최신 다운로드
더>
웹 효과
웹사이트 소스 코드
웹사이트 자료
프론트엔드 템플릿
회사 소개 부인 성명 Sitemap
PHP 중국어 웹사이트:공공복지 온라인 PHP 교육,PHP 학습자의 빠른 성장을 도와주세요!