阿里云主机折上折
  • 微信号
Current Site:Index > Build tool configuration

Build tool configuration

Author:Chuan Chen 阅读数:62067人阅读 分类: 前端综合

The Necessity of Engineering Standards

The complexity of modern front-end projects continues to increase, with code volume growing exponentially. Engineering standards have become the foundational guarantee for team collaboration and project maintenance, effectively addressing issues such as chaotic code styles, dependency management difficulties, and inefficient builds. Unified standards ensure consistency in code written by different developers, reducing communication costs and improving code maintainability.

Code Standard Tool Configuration

ESLint Configuration Example

ESLint is currently the most popular JavaScript code linting tool. Team-wide code style can be defined through the .eslintrc.js configuration file:

module.exports = {
  env: {
    browser: true,
    es2021: true
  },
  extends: [
    'eslint:recommended',
    'plugin:@typescript-eslint/recommended',
    'prettier'
  ],
  parser: '@typescript-eslint/parser',
  parserOptions: {
    ecmaVersion: 'latest',
    sourceType: 'module'
  },
  rules: {
    'no-console': 'warn',
    'quotes': ['error', 'single'],
    'semi': ['error', 'always'],
    'indent': ['error', 2]
  }
};

Prettier Integration

Prettier, as a code formatting tool, can be used in conjunction with ESLint. Example .prettierrc configuration:

{
  "printWidth": 80,
  "tabWidth": 2,
  "useTabs": false,
  "semi": true,
  "singleQuote": true,
  "trailingComma": "es5"
}

Add a formatting script to package.json:

{
  "scripts": {
    "format": "prettier --write \"src/**/*.{js,ts,jsx,tsx}\""
  }
}

Build Tool Basic Configuration

Webpack Core Configuration

Webpack is one of the most commonly used build tools for modern front-end projects. Basic configuration file webpack.config.js:

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './src/index.ts',
  output: {
    filename: 'bundle.[contenthash].js',
    path: path.resolve(__dirname, 'dist'),
    clean: true
  },
  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: /node_modules/
      },
      {
        test: /\.css$/i,
        use: ['style-loader', 'css-loader']
      }
    ]
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js']
  },
  plugins: [
    new HtmlWebpackPlugin({
      template: './public/index.html'
    })
  ]
};

Babel Transpilation Configuration

For projects requiring compatibility with older browsers, Babel configuration .babelrc:

{
  "presets": [
    ["@babel/preset-env", {
      "targets": {
        "chrome": "58",
        "ie": "11"
      },
      "useBuiltIns": "usage",
      "corejs": "3.26"
    }],
    "@babel/preset-typescript"
  ],
  "plugins": [
    "@babel/plugin-transform-runtime"
  ]
}

Advanced Build Optimization

Code Splitting Strategy

Webpack's code splitting can significantly improve application loading performance:

// webpack.config.js
module.exports = {
  //...
  optimization: {
    splitChunks: {
      chunks: 'all',
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name: 'vendors',
          chunks: 'all'
        }
      }
    }
  }
};

Tree Shaking Configuration

For ES Module projects, enable tree shaking to eliminate unused code:

// webpack.config.js
module.exports = {
  //...
  optimization: {
    usedExports: true,
    minimize: true,
    minimizer: [
      new TerserPlugin({
        terserOptions: {
          compress: {
            drop_console: true
          }
        }
      })
    ]
  }
};

Environment Variable Management

Multi-Environment Configuration Solution

Use webpack-merge to implement configurations for different environments:

// webpack.common.js
const { merge } = require('webpack-merge');

const commonConfig = {
  // Common configuration
};

module.exports = (env) => {
  const envConfig = require(`./webpack.${env.NODE_ENV}.js`);
  return merge(commonConfig, envConfig);
};

Example environment configuration file webpack.prod.js:

const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');

module.exports = {
  mode: 'production',
  devtool: 'source-map',
  optimization: {
    minimizer: [
      new CssMinimizerPlugin()
    ]
  }
};

Custom Loader and Plugin

Developing a Simple Loader

Example: Create a loader to replace strings:

// replace-loader.js
module.exports = function(source) {
  return source.replace(/Hello/g, 'Hi');
};

Usage in Webpack configuration:

module.exports = {
  //...
  module: {
    rules: [
      {
        test: /\.txt$/,
        use: [
          {
            loader: path.resolve(__dirname, 'replace-loader.js')
          }
        ]
      }
    ]
  }
};

Developing a Simple Plugin

Basic Plugin example:

class LogPlugin {
  apply(compiler) {
    compiler.hooks.done.tap('LogPlugin', (stats) => {
      console.log('Compilation completed:', stats.hash);
    });
  }
}

module.exports = {
  plugins: [
    new LogPlugin()
  ]
};

Performance Monitoring and Analysis

Build Speed Analysis

Use speed-measure-webpack-plugin to measure build time:

const SpeedMeasurePlugin = require('speed-measure-webpack-plugin');

const smp = new SpeedMeasurePlugin();

module.exports = smp.wrap({
  // webpack configuration
});

Bundle Analysis Tool

Configure webpack-bundle-analyzer:

const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;

module.exports = {
  plugins: [
    new BundleAnalyzerPlugin({
      analyzerMode: 'static',
      reportFilename: 'bundle-report.html'
    })
  ]
};

Modern Build Solutions

Vite Basic Configuration

Vite's vite.config.js example:

import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';

export default defineConfig({
  plugins: [react()],
  server: {
    port: 3000,
    open: true
  },
  build: {
    outDir: 'dist',
    assetsInlineLimit: 4096
  }
});

Rollup Configuration Example

Rollup is suitable for library development. Basic configuration rollup.config.js:

import { babel } from '@rollup/plugin-babel';
import { nodeResolve } from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';

export default {
  input: 'src/index.js',
  output: [
    {
      file: 'dist/bundle.cjs.js',
      format: 'cjs'
    },
    {
      file: 'dist/bundle.esm.js',
      format: 'esm'
    }
  ],
  plugins: [
    nodeResolve(),
    commonjs(),
    babel({ babelHelpers: 'bundled' })
  ]
};

Build Optimization in Continuous Integration

CI/CD Caching Strategy

Example of caching node_modules and build artifacts in GitHub Actions:

name: CI
on: [push]
jobs:
  build:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v2
      - uses: actions/cache@v2
        with:
          path: |
            node_modules
            dist
          key: ${{ runner.os }}-build-${{ hashFiles('**/package-lock.json') }}
      - run: npm ci
      - run: npm run build

Parallel Build Configuration

Use thread-loader to speed up builds:

module.exports = {
  module: {
    rules: [
      {
        test: /\.js$/,
        use: [
          {
            loader: 'thread-loader',
            options: {
              workers: 4
            }
          },
          'babel-loader'
        ]
      }
    ]
  }
};

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

上一篇:版本控制规范

下一篇:依赖管理规范

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.