JaneAnne's Technical Blog

website·Indexed 30 days ago

https://janeanne218.github.io/myblog2

A personal technical blog by front-end engineer Anne Jane, featuring notes and tutorials on Vue.js (including source code analysis of v2.7.14), TypeScript, Vite, VitePress, and Webpack. The content covers front-end fundamentals, DOM manipulation, Axios, CORS, regular expressions, and project implementations like MiniVue.js and various Chrome extensions, as well as guides for Ubuntu on Windows and GitHub Actions with pnpm.

Tokens
16.9K
Snippets
105
Records
120
Agent score
75%

What's inside JaneAnne's Blog

  1. Overview of axios features

    axios is a Promise-based HTTP client compatible with both the browser and Node.js. Key features include:

    • Creating XMLHttpRequests in the browser
    • Creating HTTP requests in Node.js
    • Support for the Promise API
    • Request and response interceptors
    • Request and response data transformation
    • Request cancellation
    • Automatic JSON data transformation
    • Client-side protection against XSRF
  2. Implement an API service layer for Vue components

    To maintain a clean architecture, wrap axios requests in standalone functions within an API directory. This allows components to call specific functions rather than defining raw request configurations.
    // api/home.js
    import request from "@/utils/request";
    export function getBanner() {
      return request({
        url: "/banner",
      });
    }
    
    // Home.vue
    import { getBanner } from "@/api/home";
    export default {
      name: "Home",
      data() {
        return {
          banners: [],
        };
      },
      created() {
        getBanner().then((res) => {
          this.banners = res.data.banners;
        });
      },
    };
  3. Manage Vuex state using a Player class with localStorage persistence

    In this architecture, the Vuex state is instantiated as an instance of a Player class (new Player()). This allows state logic (methods) to be encapsulated within the class and called directly from components. To prevent data loss upon page refresh, the state is synchronized with the browser's localStorage using helper methods that serialize the class instance to JSON.
    export default class Player {
      constructor() {
        // Initialize state data
        this.repeatMode = 'off';
        
        // Load persisted state from localStorage on instantiation
        this._loadSelfFromLocalStorage();
      }
    
      switchRepeatMode() {
        if (this.repeatMode === 'none') {
          this.repeatMode = 'all';
        } else if (this.repeatMode === 'all') {
          this.repeatMode = 'one';
        } else if (this.repeatMode === 'one') {
          this.repeatMode = 'none';
        }
    
        // Persist the updated state
        this._saveSelfToLocalStorage();
      }
    
      _saveSelfToLocalStorage() {
        // Save the current Player instance state to localStorage
        localStorage.setItem('player', JSON.stringify(this));
      }
    
      _loadSelfFromLocalStorage() {
        // Retrieve and merge persisted state back into the current instance
        const playerData = localStorage.getItem('player');
        if (playerData) {
          const player = JSON.parse(playerData);
          Object.assign(this, player);
        }
      }
    }
  4. Access browser information using the navigator object

    The navigator global object provides information about the browser and operating system. In Vue.js projects, it is commonly used for feature detection or checking the navigator.userAgent string to implement browser-specific behaviors or styles.
  5. Handle route parameter updates with beforeRouteUpdate

    The beforeRouteUpdate navigation guard is called when the current route is about to be updated, specifically when switching parameters within the same route (e.g., moving from /artist/1 to /artist/2).
  6. Understand the Browser Same-Origin Policy

    The Same-Origin Policy (SOP) is a critical security mechanism implemented by browsers to isolate potentially malicious files. It restricts how documents or scripts loaded from one origin can interact with resources from a different origin.
  7. Use toRefs to maintain reactivity when destructuring Pinia stores

    When extracting properties from a Pinia store object, use the toRefs function to convert the properties into reactive variables. This prevents the loss of reactivity that occurs during standard object destructuring.
  8. Configure ESLint and Prettier for a Node.js project

    Set up a linting and formatting pipeline by installing ESLint and Prettier. To prevent conflicts between ESLint and Prettier, use eslint-config-prettier and integrate Prettier as a plugin via eslint-plugin-prettier.
    # Install ESLint
    npm install eslint@7.32.0 --save-dev
    
    # Initialize ESLint configuration
    npx eslint --init
    
    # Install Prettier
    npm install --save-dev --save-exact prettier
    
    # Resolve conflicts between ESLint and Prettier
    npm install eslint-config-prettier --save-dev
    
    # Integrate Prettier as an ESLint plugin
    npm install eslint-plugin-prettier --save-dev
  9. Clone a GitHub repository into Obsidian using the Git plugin

    To clone a remote GitHub repository into your Obsidian vault using the Git plugin:

    1. Open the Command Palette using Ctrl+P and run the Git: Clone command.
    2. Enter the remote repository URL. To authenticate, use a GitHub Personal Access Token (PAT) with repo permissions. The token is generated in GitHub Settings > Developer settings > Personal access tokens.
    3. Specify a destination folder. This folder must be empty; if it does not exist, the plugin will create it.
    4. Wait for the download to complete.

    The resulting local folder is a standard Git repository and can be managed simultaneously via Obsidian, VS Code, or GitHub Desktop.

    https://<PERSONAL_ACCESS_TOKEN>@github.com/<USERNAME>/<REPO>.git
  10. Set up a basic reverse proxy server with http-proxy

    To create a reverse proxy server in Node.js, initialize a project, install the http-proxy module, and implement a server that forwards requests to a target URL. Note that the target server must use HTTP; HTTPS is not supported in this basic configuration.
    # 1. Initialize Node.js project
    npm init -y
    
    # 2. Install the proxy module
    npm install http-proxy
    const http = require('http');
    const httpProxy = require('http-proxy');
    
    // Create a reverse proxy server
    const proxyServer = httpProxy.createServer({
      target: 'http://example.com', // Set the target server
    });
    
    // Start the proxy server and listen on port 8080
    proxyServer.listen(8080, () => {
      console.log('Proxy server started, listening on port 8080...');
    });
    # 3. Start the server
    node <filename>.js
  11. Initialize a Node.js project with npm init

    Create a package.json file to define project metadata, scripts, and dependencies. For a CI/CD server project, include basic fields like name, version, and description. To link the project to a Git repository, add a repository object with the type and URL.
    {
     "name": "jane-deploy",
     "version": "1.0.0",
     "description": "CI/CD server",
     "main": "index.js",
     "scripts": {
       "test": "echo \"Error: no test specified\" && exit 1"
     },
     "keywords": [
       "ci",
       "cd",
       "deploy"
     ],
     "author": "zuoxiaobai",
     "license": "MIT",
     "repository": {
        "type": "git",
        "url": "git+https://github.com/zuoxiaobai/js-deploy.git"
      }
    }