CoderCat Documentation

website·Indexed 30 days ago

http://docs.codercat.top/

A collection of technical notes and guides covering frontend development, including TypeScript type systems, Vite and VitePress configuration and deployment, JavaScript interview implementations, and bugfix records for Vben Admin, ElementUI, and Uni-app.

Tokens
15.7K
Snippets
72
Records
92
Agent score
50%

What's inside CoderCat Docs

  1. Understand TypeScript's relationship to JavaScript

    TypeScript is a superset of JavaScript that adds a type system and additional features such as interfaces, generics, and decorators. Its primary goal is to enhance JavaScript's capabilities to make it more suitable for large-scale, collaborative enterprise projects rather than replacing JavaScript with a completely new language.
  2. Understand the relationship between TypeScript types and JavaScript values

    TypeScript distinguishes between 'values' and 'types'. Type declarations exist only for static analysis and are completely removed during the compilation process. The resulting JavaScript contains only 'value code'. Because of this, all valid JavaScript is also valid TypeScript, allowing for gradual migration of legacy JS projects to TS.
  3. Use TypeScript type inference

    Type declarations are optional. If omitted, TypeScript automatically infers the type based on the assigned value. Once a type is inferred, assigning a value of a different type will trigger a compile-time error. This also applies to function return values.
    // Inferred as number
    let age = 123;
    age = "hello"; // Error: Type 'string' is not assignable to type 'number'
    
    // Inferred return type: string
    function toString(num: number) {
      return String(num);
    }
  4. Call generic functions with explicit or inferred type parameters

    TypeScript can often infer the type parameter T from the arguments provided. However, in complex scenarios or when using union types to combine different input types, you must explicitly provide the type parameter in angle brackets during the function call.
    function comb<T>(arr1: T[], arr2: T[]): T[] {
      return arr1.concat(arr2);
    }
    
    // Explicitly providing a union type to allow different input types
    comb<number | string>([1, 2], ["a", "b"]);
    
    // Multiple type parameters
    function map<T, U>(arr: T[], f: (arg: T) => U): U[] {
      return arr.map(f);
    }
    map<string, number>(["1", "2", "3"], (n) => parseInt(n));
  5. Install and initialize VitePress

    To set up VitePress, you must have Node.js version > 18 installed. First, add VitePress as a development dependency, then run the initialization wizard to configure your site title, description, theme, and TypeScript preferences.
    # Install VitePress
    npm add -D vitepress
    
    # Initialize the project
    npx vitepress init
  6. Resolve 'Could not find a declaration file for module' error when importing JS files in TypeScript

    When importing a .js file explicitly in a TypeScript environment (e.g., <script setup lang="ts">), TypeScript treats it as a pure JavaScript module. By default, it does not perform type inference on the code but instead looks for a matching .d.ts declaration file. If no declaration file exists, it throws the error: "Could not find a declaration file for module 'XXX', implicitly has an 'any' type".

    To fix this, change the file extension of the imported module from .js to .ts. TypeScript will then perform type inference on the file. When importing without an explicit extension, TypeScript resolves files in the order: .ts -> .d.ts -> .js.

    <script setup lang="ts">
      // Change from '@/utils/parse.js' to '@/utils/parse'
      import { parse } from '@/utils/parse';
    </script>
  7. Deploy and configure Minio on 1Panel

    Follow these steps to deploy Minio for object storage:

    Prerequisites:

    • Open ports 9000 and 9001 on the server firewall.

    Installation and Setup:

    1. Install Minio from the Application Store and set the username and password.
    2. Enable External Port Access (端口外部访问). Set the Console port to 9001 and the API port to 9000 (these can be customized).
    3. Access the Minio console via http://[Your Server IP]:9001 and log in.

    Post-Installation Configuration:

    1. Region: Go to Configuration > Region and set the Server Location to zh-east-1.
    2. Bucket: Go to Buckets and click Create Bucket to create a new storage bucket.
    3. Keys: Go to Access Keys and click Create access key. Save the generated Access Key and Secret Key for use in remote file synchronization.
  8. Prepare VitePress for GitHub Pages deployment

    Before deploying to GitHub Pages, perform these two essential configuration steps to ensure assets load correctly and GitHub does not process the site with Jekyll:

    1. Set the base path: In your VitePress configuration, add a base option set to your repository name (e.g., /repository-name/). This ensures that internal links and assets resolve correctly when hosted at a subpath.
    2. Disable Jekyll: Create an empty file named .nojekyll in the root directory of your project. This tells GitHub Pages to skip the Jekyll processing step, which is necessary for VitePress sites to render CSS and other assets correctly.
  9. Implement image zooming in VitePress using medium-zoom

    To add image zooming functionality to a VitePress site, use the medium-zoom library. This requires initializing the zoom effect on the .main img selector and ensuring it re-initializes when the route changes to handle dynamic content loading.
    npm install medium-zoom
    // .vitepress/theme/index.ts
    import Theme from "vitepress/theme";
    import mediumZoom from 'medium-zoom';
    import { nextTick, onMounted, watch } from 'vue';
    import { useRoute } from 'vitepress'
    
    export default {
      ...Theme,
      setup() {
        const route = useRoute()
        const initZoom = () => {
          mediumZoom('.main img', { background: 'var(--vp-c-bg)' })
        }
        onMounted(() => {
          initZoom()
        })
        watch(
          () => route.path,
          () => nextTick(() => initZoom())
        )
      },
    };
  10. Declare complex structures and mixed-type arrays in TypeScript

    For complex data structures, you can combine object and array types. To allow an array to contain multiple different types, use a union type or the any type.
    // Two-dimensional array (tuple array)
    const arr1: [string, number][] = [["Tom", 18], ["Jack", 20]];
    
    // Array of objects
    const arr2: { name: string, age: number }[] = [{ name: "Tom", age: 18 }, { name: "Jack", age: 20 }];
    
    // Array with union types (string OR object)
    const arr3: (string | { name: string; age: number })[] = [
        "Tom", 
        { name: "Tom", age: 18 }
    ];
    
    // Array with any type (allows any structure)
    const arr4: any[] = [
        "Boy", 
        [
            "Tom", 
            { name: "Tom", age: 18 }, 
            { name: "Jack", age: 20 }
        ]
    ];
  11. Resolve 'Could not find a declaration file for module' error when importing JS files

    In TypeScript (e.g., within a Vue <script setup lang="ts"> block), explicitly importing a file with a .js extension causes TypeScript to treat it as a plain JavaScript module. By default, TS will not perform type inference on the code but will look for a corresponding .d.ts declaration file. If no declaration file exists, it throws the error: 'Could not find a declaration file for module "XXX", implicitly has "any" type'.

    To fix this, rename the target file from .js to .ts. TypeScript will then perform type inference on the file. When importing without an extension, TypeScript resolves files in the order: .ts -> .d.ts -> .js.

    <script setup lang="ts">
      // Change this:
      import { parse } from '@/utils/parse.js';
      
      // To this (and rename parse.js to parse.ts):
      import { parse } from '@/utils/parse';
    </script>
  12. Enable GitHub Actions as the source for GitHub Pages

    After pushing your code and the deploy.yml workflow to GitHub, you must tell GitHub to use Actions for deployment instead of a specific branch:

    1. Go to your repository on GitHub.
    2. Navigate to Settings > Pages.
    3. Under Build and deployment > Source, select GitHub Actions from the dropdown menu.