renchao8697 Learning Notes

website·Indexed 29 days ago

https://renchao8697.github.io/note

A collection of technical notes covering frontend development and backend infrastructure. Topics include JavaScript (ES6 Proxy, Reflect, and data structures), HTML, CSS, and frameworks like Vue 2, Vue 3, React, and Webpack. It also covers HTTP protocols (CORS, caching, and headers), databases (SQL, Redis, and MongoDB), and common interview questions.

Tokens
19.4K
Snippets
93
Records
113
Agent score
75%

What's inside renchao8697 Notes

  1. Overview of Set (Collection) in JavaScript

    A Set is a collection of unique, unordered elements. In ES6, the Set type is provided. A typical Set implementation should support: values (all elements), size (count), has (existence check), add (insert), remove (delete), union (combine two sets), intersection (common elements), difference (elements in one but not the other), and subset (check if one set is contained within another).
  2. Understand HTTP Header categories

    HTTP headers allow clients and servers to pass additional information via requests and responses. They are formatted as a case-insensitive name followed by a colon (:) and a value. Headers are categorized by their context:

    • General Headers: Applied to both requests and responses but are unrelated to the actual data being transported in the message body (e.g., Date, Cache-Control, Connection).
    • Request Headers: Provide information about the resource to be fetched or the client itself (e.g., Accept, Cookie, User-Agent, Referer).
    • Response Headers: Provide supplementary information about the response, such as its location or the server details (e.g., Age, Location, Server).
    • Entity Headers: Describe the metadata of the message payload/body (e.g., Content-Length, Content-Type, Content-Encoding, Expires). These can appear in both requests and responses.
  3. Understand the Webpack build process

    Webpack executes a serial build process consisting of the following steps:

    1. Parameter Initialization: Merges configuration files and Shell arguments.
    2. Compilation Start: Initializes the Compiler object, loads plugins, and executes the run method.
    3. Entry Determination: Identifies all entry files based on the entry configuration.
    4. Module Compilation: Recursively translates modules using configured loaders and resolves their dependencies.
    5. Compilation Completion: Produces the final translated content for each module and maps their dependency relationships.
    6. Resource Output: Groups modules into Chunks and converts them into individual files for the output list.
    7. Output Completion: Writes the final files to the file system based on the configured path and filename.

    Throughout this process, Webpack broadcasts events that plugins can listen to and use to modify the build result via Webpack APIs.

  4. Create a basic Proxy to intercept object operations

    The Proxy object allows you to create a proxy for another object, enabling the interception and customization of fundamental operations such as property lookup, assignment, enumeration, and function calls. A proxy consists of a target object and a handler object containing 'traps'.
    const target = {
      id: 'target'
    };
    const handler = {};
    const proxy = new Proxy(target, handler);
    
    // Operations on proxy reflect on target and vice versa
    console.log(proxy.id); // 'target'
    proxy.id = 'bar';
    console.log(target.id); // 'bar'
  5. Understand the Same-Origin Policy (SOP)

    The Same-Origin Policy is a security mechanism that restricts how a document or script from one origin can interact with resources from another origin. Two URLs are considered 'same-origin' only if their protocol, port, and host are all identical.
  6. Understand Webpack core concepts

    Webpack is a static module bundler that recursively builds a dependency graph from entry points to bundle all required modules into static assets. Key terms include:

    • entry: The starting point for the dependency graph.
    • output: Where the resulting bundles are written and how they are named.
    • mode: Specifies the target environment (e.g., development, production) to enable built-in optimizations.
    • loader: Transforms non-JavaScript files (like CSS or images) into valid modules.
    • plugin: Extends Webpack's functionality for broader tasks like bundle optimization, asset management, and environment variable injection.
    • chunk: A group of modules used for code splitting and merging.
    • bundle: The final output file after compilation.
    • module: A single file in the project; Webpack treats everything as a module.
  7. Understand the JavaScript Engine architecture and execution flow

    The JavaScript engine converts source code into machine code through the following process:

    1. Parser: Reads the code and generates an Abstract Syntax Tree (AST) stored in memory.
    2. Interpreter: Processes the AST to generate bytecode or machine code.
    3. Profiler: Monitors code execution to identify "hot functions."
    4. JIT (Just-in-Time) Compiler: Uses profiling data to produce highly optimized machine code. If assumptions are wrong, it performs a "Deoptimize" phase to revert to a previous version.
    5. Memory Management: The call stack tracks executing functions, the memory heap handles allocation, and the Garbage Collector reclaims memory from unused objects.
  8. Implement a Hash Table in JavaScript

    A Hash Table is a data structure used to store key-value pairs. It uses a hash function to convert a key into a numeric index, allowing for highly efficient value retrieval with a time complexity of O(1). The hash function must ensure that the same input always produces the same output, and different inputs produce different outputs (acting as a unique fingerprint). A standard Hash Table implementation should provide the following operations: add to insert a key-value pair, remove to delete a pair, and lookup to retrieve a value associated with a specific key.
  9. Understand the HTTP caching workflow

    HTTP caching is divided into two main categories: Strong Caching and Negotiated (Conditional) Caching. When a browser requests a resource, it follows this logic:

    1. Strong Cache Check: The browser first checks if a strong cache hit occurs. If it does, the resource is loaded directly from the local cache without sending a request to the server.
    2. Negotiated Cache Check: If the strong cache is missing or expired, the browser sends a request to the server. The server validates the resource using specific request headers. If the resource is still valid, the server returns a 304 Not Modified status, and the browser uses the cached version. Otherwise, the server returns the full updated resource.
  10. Follow best practices when writing Webpack loaders

    To ensure maintainability and performance, follow these guidelines when developing loaders:

    • Simple & Chaining: Loaders should perform a single task. Use multiple simple loaders in a chain rather than one complex loader.
    • Modular & Stateless: Ensure the output is modular and that the loader does not preserve state between different modules or compilation runs.
    • Dependencies: Use this.addDependency(path) to declare external resources used by the loader so Webpack can invalidate caches and trigger re-compilation in watch mode.
    • Module Resolution: Resolve dependencies (like @import in CSS) by converting them to require statements or using this.resolve.
    • Avoid Absolute Paths: Use loader-utils's stringifyRequest to convert absolute paths to relative paths to ensure portability across different project roots.
    • Common Code: Do not inject duplicate common code into every module. Instead, create a runtime file and use require to reference it.
    • Peer Dependencies: If your loader wraps another package, list that package as a peerDependency in package.json to allow users to specify the version.
    import path from 'path';
    
    export default function (source) {
      var callback = this.async();
      var headerPath = path.resolve('header.js');
    
      // Declare dependency for cache invalidation and watch mode
      this.addDependency(headerPath);
    
      fs.readFile(headerPath, 'utf-8', function (err, header) {
        if (err) return callback(err);
        callback(null, header + '\n' + source);
      });
    }
  11. Handle CORS Preflight requests with OPTIONS

    Browsers automatically send a preflight request using the OPTIONS method to check if the server supports CORS before sending the actual request (e.g., for DELETE requests or requests with custom headers). The preflight request includes Access-Control-Request-Method, Access-Control-Request-Headers, and Origin headers.
    // Preflight Request
    OPTIONS /resource/foo
    Access-Control-Request-Method: DELETE
    Access-Control-Request-Headers: origin, x-requested-with
    Origin: https://foo.bar.org
    
    // Server Response
    HTTP/1.1 200 OK
    Access-Control-Allow-Origin: https://foo.bar.org
    Access-Control-Allow-Methods: POST, GET, OPTIONS, DELETE
    Access-Control-Max-age: 86400
  12. Understand the setup context and return values

    The context argument in setup(props, context) is a non-reactive plain JavaScript object. It provides access to props, attrs, slots, and emit, but does not provide access to data, computed, methods, or refs.

    If setup returns an object, its properties (and the component's props) are available in the template. Refs returned from setup are automatically unwrapped in the template, so .value should not be used there.