搜索...
pnpm init -y
pnpm add typescript -D
pnpm add tsup -D
tsup.config.ts
import type { Options } from "tsup"; const config: Options = { entry: ["src/index.ts"], dts: true, sourcemap: true, format: ["iife", "cjs", "esm"], clean: true, }; export default config;
{ "type": "module", "main": "./dist/index.js", "module": "./dist/index.js", "exports": { "require": "./dist/index.cjs", "import": "./dist/index.js", "default": "./dist/index.cjs", "node": "./dist/index.cjs" "types": "./dist/index.d.ts", }, "scripts": { "build": "tsup src/index.ts", "start": "npm run build -- --watch", "test": "echo \"Error: no test specified\" && exit 1" } }
pnpm add jest jest-environment-jsdom ts-jest @testing-library/react @testing-library/react-hooks @types/node react-test-renderer ts-node tslib -D
import { useEffect, useState, useCallback } from "react"; type Size = { width?: number; height?: number }; const useWindowSize = () => { const [state, setState] = useState<Size>(() => { const { clientWidth, clientHeight } = (document as Document) .documentElement; return { width: clientWidth, height: clientHeight, }; }); const onResize = useCallback(() => { const { clientWidth, clientHeight } = (document as Document) .documentElement; setState({ width: clientWidth, height: clientHeight, }); }, []); useEffect(() => { window.addEventListener("resize", onResize, false); return () => { window.removeEventListener("resize", onResize, false); }; }, []); return state; }; export default useWindowSize;
import { renderHook } from "@testing-library/react-hooks"; import useWindowSize from "../index"; describe("useWindowSize", () => { it("should be defined", () => { expect(useWindowSize).toBeDefined(); }); it("with argument", () => { const hook = renderHook(() => useWindowSize()); expect(hook.result.current.width).toEqual(0); expect(hook.result.current.height).toEqual(0); }); });