KeyToLove Blog

website·Indexed 30 days ago

https://keytolove.github.io/

A technical blog by a frontend engineer featuring articles on webpack 5.x, frontend request Mocking schemes, LeetCode algorithm solutions, CLI scaffolding, and source code analysis of React-dev-inspector.

Tokens
11.3K
Snippets
51
Records
60
Agent score
75%

What's inside KeyToLove

  1. Request a friendly link on KeyToLove blog

    To request a friendly link (友情链接) on the KeyToLove blog, submit a GitHub issue to the repository providing the following required information: nickname, avatar URL, and a brief introduction.
    昵称: Mike
    头像地址: http://example.jpg
    简介: 大帅比一个
  2. Webpack 5 Core Concepts Overview

    Webpack is a static module bundler for modern JavaScript applications. It builds a dependency graph of the project and generates one or more bundles. The four core concepts are:

    1. entry: The entry point to the application.
    2. output: Where the bundled files are emitted.
    3. loader: Module transformers that allow pre-processing of files during import/load.
    4. plugins: Extensions that perform tasks loaders cannot.
  3. Understand the LRU (Least Recently Used) Cache algorithm

    LRU (Least Recently Used) is a cache replacement algorithm that removes the least recently accessed items first when the cache reaches its capacity limit. It is commonly used in system memory management, page replacement algorithms, and caching services like Redis or Memcached. The core logic is to maintain an order of access; when a new item is added to a full cache, the item that has not been accessed for the longest time is evicted.
  4. Implement frontend mocking using a custom Axios adapter

    This approach intercepts requests within the Axios instance. It allows for a global mock toggle via environment variables and avoids sending actual HTTP requests when mocking is enabled. It is ideal for quick development where a full server is not required.
    # package.json: Add a script to enable mocking via environment variable
    "scripts": {
      "dev": "vue-cli-service serve",
      "dev:mock": "cross-env IS_MOCK=true vue-cli-service serve"
    }
    // vue.config.js: Inject IS_MOCK into the global scope
    const IS_MOCK = process.env.IS_MOCK === 'true'
    module.exports = {
      chainWebpack: config => {
        config.plugin('define').tap(args => {
          args[0].IS_MOCK = IS_MOCK
          return args
        })
      }
    }
    // mock.js: Define mock data mapped by URL
    module.exports = {
      '/products': {
        code: 0,
        data: [{ id: 001, name: 'Product 1' }],
        message: 'success',
      },
    }
    // axios-instance.js: Create axios instance with custom adapter
    import axios from 'axios'
    const mockMap = require('./mock.js')
    
    var instance = axios.create({
      adapter: config => {
        if (mockMap[config.url] && IS_MOCK) {
          return Promise.resolve({
            data: mockMap[config.url],
            status: 200,
          })
        } else {
          delete config.adapter // Prevent infinite loop
          return axios(config)
        }
      },
    })
    export default instance
  5. Copy static assets that should bypass Webpack bundling

    For assets that should not be processed by Webpack (e.g., external SDKs in a public folder), use copy-webpack-plugin to copy files directly from the source directory to the build output directory.
    npm i copy-webpack-plugin -D
    // webpack.config.js
    const CopyWebpackPlugin = require('copy-webpack-plugin');
    
    module.exports = {
      // ...
      plugins: [
        new CopyWebpackPlugin({
          patterns: [
            {
              from: 'public/js/*.js',
              to: 'js/[name][ext]',
            },
          ],
        }),
      ],
    };
  6. Register a Node.js script as an executable CLI command

    To make a Node.js script executable as a CLI command, you must specify the interpreter and map the command to the entry file in the project configuration.
    // 1. Add this shebang to the very top of index.js
    #!/usr/bin/env node
    // 2. Update package.json
    {
      "name": "create-web-app",
      "version": "1.0.0",
      "type": "module",
      "bin": "index.js"
    }
  7. Initialize a basic Webpack 5 project

    To set up a basic Webpack 5 project, install webpack and webpack-cli as development dependencies. Create a webpack.config.js file to define the entry point and output destination.
    # Install dependencies
    npm i webpack webpack-cli -D
    // webpack.config.js
    const path = require('path');
    
    module.exports = {
      // Default is ./src/index.js
      entry: './src/index.js',
      // Default output is dist/main.js
      output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'bundle.[contenthash:6].js',
      },
    };
  8. Configure JS backward compatibility with Babel

    To ensure JavaScript compatibility with older browsers (e.g., IE11), use babel-loader along with @babel/core and @babel/preset-env. This transforms modern ES6+ syntax (like const) into compatible versions (like var).
    npm i babel-loader @babel/core @babel/preset-env core-js -D
    // webpack.config.js
    module.exports = {
      module: {
        rules: [
          {
            test: /\.jsx?$/,
            loader: 'babel-loader',
            exclude: /node_modules/,
          },
        ],
      },
    };
    // .babelrc
    {
      "presets": [
        [
          "@babel/preset-env",
          {
            "targets": {
              "chrome": "58",
              "ie": "11"
            },
            "corejs": "3",
            "useBuiltIns": "usage"
          }
        ]
      ]
    }
  9. Distribute and run a custom CLI tool

    Once the CLI tool is developed, you can use it in two ways:

    1. Local Development: Use npm link to link the project to the global npm environment. You can then run the command (e.g., create-web-app) directly from the terminal.
    2. Production: Publish the package to the npm registry, install it globally via npm install -g <package-name>, and run the command from the terminal.
  10. Set up a development server for real-time preview

    Install webpack-dev-server to launch a local development server that supports hot reloading. Configure the devServer object in webpack.config.js to customize the port and compression settings.
    npm install webpack-dev-server -D
    // package.json
    {
      "scripts": {
        "dev": "webpack serve"
      }
    }
    // webpack.config.js
    module.exports = {
      devServer: {
        port: '9000',
        compress: true, // Enable gzip compression
      },
    };
  11. Handle images and font files using url-loader

    To process image and font assets, use url-loader. This allows you to convert small files into base64 strings to reduce HTTP requests and specify custom naming and output paths for larger files.
    npm install url-loader -D
    // webpack.config.js
    module.exports = {
      // ...
      module: {
        rules: [
          {
            test: /\.(png|jpg|gif|jpeg|webp|svg|eot|ttf|woff|woff2)$/,
            use: [
              {
                loader: 'url-loader',
                options: {
                  limit: 10240, // Files smaller than 10K are converted to base64
                  esModule: false,
                  name: '[name]_[contenthash:6].[ext]',
                  outputPath: 'assets/images',
                },
              },
            ],
            exclude: /node_modulesๆ/,
          },
        ],
      },
    };