构建工具

构建工具概述

构建工具是现代前端开发的重要组成部分,能自动化处理代码转换、压缩、优化等任务,提高开发效率和代码质量。

东巴文(db-w.cn) 认为:构建工具就像工厂的流水线,能自动化完成繁琐的任务,让开发者专注于业务逻辑。选择合适的构建工具,能大幅提升开发效率。

构建工具的作用

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>构建工具概述 - 东巴文</title>
    
    <style>
        body {
            font-family: 'Segoe UI', sans-serif;
            padding: 20px;
            background: #f5f5f5;
        }
        
        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            padding: 30px;
            border-radius: 10px;
        }
        
        h1 {
            color: #667eea;
            margin-bottom: 20px;
        }
        
        h2 {
            color: #764ba2;
            margin: 30px 0 15px;
            border-left: 4px solid #764ba2;
            padding-left: 15px;
        }
        
        .tool-demo {
            background: #f8f9fa;
            padding: 20px;
            border: 2px solid #ddd;
            margin: 15px 0;
            border-radius: 10px;
        }
        
        .tool-demo h3 {
            color: #667eea;
            margin-bottom: 10px;
        }
        
        .feature-list {
            list-style: none;
            padding: 0;
        }
        
        .feature-list li {
            padding: 8px 0;
            border-bottom: 1px solid #eee;
        }
        
        .feature-list li:before {
            content: "✓ ";
            color: #667eea;
            font-weight: bold;
        }
        
        .tool-table {
            width: 100%;
            border-collapse: collapse;
            margin: 20px 0;
        }
        
        .tool-table th,
        .tool-table td {
            padding: 12px;
            text-align: left;
            border: 1px solid #ddd;
        }
        
        .tool-table th {
            background: #667eea;
            color: white;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>构建工具概述</h1>
        
        <h2>构建工具的作用</h2>
        
        <div class="tool-demo">
            <h3>主要功能</h3>
            <ul class="feature-list">
                <li><strong>代码转换:</strong> 将ES6+、TypeScript、JSX等转换为浏览器兼容的代码</li>
                <li><strong>文件优化:</strong> 压缩HTML、CSS、JavaScript文件,减小文件大小</li>
                <li><strong>模块打包:</strong> 将多个模块打包成一个或多个文件</li>
                <li><strong>代码分割:</strong> 按需加载代码,提高页面加载速度</li>
                <li><strong>资源管理:</strong> 处理图片、字体等静态资源</li>
                <li><strong>开发服务器:</strong> 提供本地开发服务器和热更新功能</li>
                <li><strong>代码检查:</strong> 集成ESLint、StyleLint等代码检查工具</li>
                <li><strong>自动化任务:</strong> 自动执行重复性任务,如编译、测试、部署</li>
            </ul>
        </div>
        
        <h2>主流构建工具</h2>
        
        <table class="tool-table">
            <thead>
                <tr>
                    <th>工具</th>
                    <th>特点</th>
                    <th>适用场景</th>
                </tr>
            </thead>
            <tbody>
                <tr>
                    <td><strong>Webpack</strong></td>
                    <td>功能强大,生态丰富,配置灵活</td>
                    <td>大型项目,复杂应用</td>
                </tr>
                <tr>
                    <td><strong>Vite</strong></td>
                    <td>快速启动,热更新快,配置简单</td>
                    <td>新项目,Vue/React应用</td>
                </tr>
                <tr>
                    <td><strong>Parcel</strong></td>
                    <td>零配置,快速,易用</td>
                    <td>小型项目,快速原型</td>
                </tr>
                <tr>
                    <td><strong>Rollup</strong></td>
                    <td>打包体积小,Tree-shaking好</td>
                    <td>库开发,组件库</td>
                </tr>
                <tr>
                    <td><strong>esbuild</strong></td>
                    <td>极快的构建速度</td>
                    <td>需要快速构建的项目</td>
                </tr>
            </tbody>
        </table>
        
        <h2>构建流程</h2>
        
        <div class="tool-demo">
            <h3>典型构建流程</h3>
            <div style="background: #2d2d2d; color: #f8f8f2; padding: 15px; border-radius: 5px; margin: 10px 0;">
                <pre>
源代码
  ↓
代码转换(ES6+ → ES5, TypeScript → JavaScript)
  ↓
模块打包(合并模块,处理依赖)
  ↓
代码优化(压缩,Tree-shaking,代码分割)
  ↓
资源处理(图片,字体,CSS)
  ↓
输出文件(dist目录)
                </pre>
            </div>
        </div>
        
        <div style="background: #fff3cd; padding: 15px; border-radius: 5px; margin-top: 20px;">
            <strong>东巴文提示:</strong>构建工具是现代前端开发的基石。根据项目需求选择合适的构建工具,掌握基本配置和优化技巧,能大幅提升开发效率和代码质量。
        </div>
    </div>
</body>
</html>

Webpack基础

Webpack是目前最流行的前端构建工具,功能强大,生态丰富,适合大型项目。

Webpack配置

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Webpack基础 - 东巴文</title>
    
    <style>
        body {
            font-family: 'Segoe UI', sans-serif;
            padding: 20px;
            background: #f5f5f5;
        }
        
        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            padding: 30px;
            border-radius: 10px;
        }
        
        h1 {
            color: #667eea;
            margin-bottom: 20px;
        }
        
        h2 {
            color: #764ba2;
            margin: 30px 0 15px;
            border-left: 4px solid #764ba2;
            padding-left: 15px;
        }
        
        .webpack-demo {
            background: #f8f9fa;
            padding: 20px;
            border: 2px solid #ddd;
            margin: 15px 0;
            border-radius: 10px;
        }
        
        .webpack-demo h3 {
            color: #667eea;
            margin-bottom: 10px;
        }
        
        .code-block {
            background: #2d2d2d;
            color: #f8f8f2;
            padding: 15px;
            border-radius: 5px;
            overflow-x: auto;
            margin: 10px 0;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Webpack基础</h1>
        
        <h2>安装Webpack</h2>
        
        <div class="webpack-demo">
            <h3>安装命令</h3>
            <div class="code-block">
                <pre>
# 安装Webpack和Webpack CLI
npm install --save-dev webpack webpack-cli

# 安装开发服务器
npm install --save-dev webpack-dev-server

# 检查版本
npx webpack --version
                </pre>
            </div>
        </div>
        
        <h2>基本配置</h2>
        
        <div class="webpack-demo">
            <h3>webpack.config.js</h3>
            <div class="code-block">
                <pre>
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    // 入口文件
    entry: './src/index.js',
    
    // 输出配置
    output: {
        filename: 'bundle.[contenthash].js',
        path: path.resolve(__dirname, 'dist'),
        clean: true, // 清理dist目录
        publicPath: '/'
    },
    
    // 模式
    mode: 'development', // development 或 production
    
    // 开发服务器
    devServer: {
        static: './dist',
        hot: true,
        open: true,
        port: 3000,
        compress: true
    },
    
    // 模块规则
    module: {
        rules: [
            // CSS处理
            {
                test: /\.css$/i,
                use: ['style-loader', 'css-loader']
            },
            
            // 图片处理
            {
                test: /\.(png|svg|jpg|jpeg|gif)$/i,
                type: 'asset/resource'
            },
            
            // 字体处理
            {
                test: /\.(woff|woff2|eot|ttf|otf)$/i,
                type: 'asset/resource'
            },
            
            // JavaScript处理
            {
                test: /\.js$/,
                exclude: /node_modules/,
                use: {
                    loader: 'babel-loader',
                    options: {
                        presets: ['@babel/preset-env']
                    }
                }
            }
        ]
    },
    
    // 插件
    plugins: [
        new HtmlWebpackPlugin({
            template: './src/index.html',
            title: '我的应用',
            filename: 'index.html'
        })
    ],
    
    // 优化
    optimization: {
        splitChunks: {
            chunks: 'all'
        }
    },
    
    // 解析
    resolve: {
        extensions: ['.js', '.json'],
        alias: {
            '@': path.resolve(__dirname, 'src')
        }
    },
    
    // source map
    devtool: 'inline-source-map'
};
                </pre>
            </div>
        </div>
        
        <h2>常用Loader</h2>
        
        <div class="webpack-demo">
            <h3>Loader配置</h3>
            <div class="code-block">
                <pre>
// CSS相关
npm install --save-dev style-loader css-loader

// Sass/SCSS
npm install --save-dev sass-loader sass

// Less
npm install --save-dev less-loader less

// Babel
npm install --save-dev babel-loader @babel/core @babel/preset-env

// TypeScript
npm install --save-dev ts-loader typescript

// 文件处理
// Webpack 5内置了asset模块,无需额外loader

// 配置示例
module: {
    rules: [
        // SCSS处理
        {
            test: /\.scss$/i,
            use: ['style-loader', 'css-loader', 'sass-loader']
        },
        
        // TypeScript处理
        {
            test: /\.tsx?$/,
            use: 'ts-loader',
            exclude: /node_modules/
        },
        
        // Babel处理
        {
            test: /\.js$/,
            exclude: /node_modules/,
            use: {
                loader: 'babel-loader',
                options: {
                    presets: [
                        ['@babel/preset-env', {
                            targets: {
                                browsers: ['&gt; 1%', 'last 2 versions']
                            }
                        }]
                    ]
                }
            }
        }
    ]
}
                </pre>
            </div>
        </div>
        
        <h2>常用插件</h2>
        
        <div class="webpack-demo">
            <h3>插件配置</h3>
            <div class="code-block">
                <pre>
// 安装插件
npm install --save-dev html-webpack-plugin
npm install --save-dev mini-css-extract-plugin
npm install --save-dev css-minimizer-webpack-plugin
npm install --save-dev terser-webpack-plugin

const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');

module.exports = {
    plugins: [
        // HTML插件
        new HtmlWebpackPlugin({
            template: './src/index.html',
            title: '我的应用',
            minify: {
                removeComments: true,
                collapseWhitespace: true
            }
        }),
        
        // CSS提取插件
        new MiniCssExtractPlugin({
            filename: 'styles.[contenthash].css'
        })
    ],
    
    optimization: {
        minimizer: [
            // CSS压缩
            new CssMinimizerPlugin(),
            // JS压缩(Webpack 5生产模式默认启用)
            '...' // 使用默认的TerserPlugin
        ]
    }
};
                </pre>
            </div>
        </div>
        
        <h2>运行Webpack</h2>
        
        <div class="webpack-demo">
            <h3>npm脚本</h3>
            <div class="code-block">
                <pre>
{
    "scripts": {
        "build": "webpack --mode production",
        "dev": "webpack serve --mode development",
        "watch": "webpack --watch"
    }
}

// 运行命令
npm run build    // 生产构建
npm run dev      // 开发服务器
npm run watch    // 监听模式
                </pre>
            </div>
        </div>
        
        <div style="background: #fff3cd; padding: 15px; border-radius: 5px; margin-top: 20px;">
            <strong>东巴文提示:</strong>Webpack功能强大但配置复杂。从基础配置开始,逐步掌握Loader、Plugin、优化等高级功能,能构建出高性能的前端应用。
        </div>
    </div>
</body>
</html>

Vite快速入门

Vite是新一代前端构建工具,开发服务器启动极快,热更新迅速,配置简单。

Vite配置

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Vite快速入门 - 东巴文</title>
    
    <style>
        body {
            font-family: 'Segoe UI', sans-serif;
            padding: 20px;
            background: #f5f5f5;
        }
        
        .container {
            max-width: 800px;
            margin: 0 auto;
            background: white;
            padding: 30px;
            border-radius: 10px;
        }
        
        h1 {
            color: #667eea;
            margin-bottom: 20px;
        }
        
        h2 {
            color: #764ba2;
            margin: 30px 0 15px;
            border-left: 4px solid #764ba2;
            padding-left: 15px;
        }
        
        .vite-demo {
            background: #f8f9fa;
            padding: 20px;
            border: 2px solid #ddd;
            margin: 15px 0;
            border-radius: 10px;
        }
        
        .vite-demo h3 {
            color: #667eea;
            margin-bottom: 10px;
        }
        
        .code-block {
            background: #2d2d2d;
            color: #f8f8f2;
            padding: 15px;
            border-radius: 5px;
            overflow-x: auto;
            margin: 10px 0;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>Vite快速入门</h1>
        
        <h2>Vite概述</h2>
        
        <div class="vite-demo">
            <h3>Vite特点</h3>
            <ul>
                <li><strong>快速启动:</strong> 开发服务器启动时间极短</li>
                <li><strong>即时热更新:</strong> 无论项目大小,热更新都很快</li>
                <li><strong>按需编译:</strong> 只编译当前页面需要的代码</li>
                <li><strong>配置简单:</strong> 开箱即用,无需复杂配置</li>
                <li><strong>优化构建:</strong> 生产构建使用Rollup,输出优化</li>
            </ul>
        </div>
        
        <h2>创建项目</h2>
        
        <div class="vite-demo">
            <h3>初始化项目</h3>
            <div class="code-block">
                <pre>
# 使用npm创建项目
npm create vite@latest my-project

# 使用yarn创建项目
yarn create vite my-project

# 使用pnpm创建项目
pnpm create vite my-project

# 选择框架
? Select a framework: 
  vanilla      # 原生JavaScript
  vue          # Vue.js
  react        # React
  preact       # Preact
  lit          # Lit
  svelte       # Svelte

# 选择变体
? Select a variant:
  vanilla
  vanilla-ts   # TypeScript

# 进入项目目录
cd my-project

# 安装依赖
npm install

# 启动开发服务器
npm run dev
                </pre>
            </div>
        </div>
        
        <h2>Vite配置</h2>
        
        <div class="vite-demo">
            <h3>vite.config.js</h3>
            <div class="code-block">
                <pre>
import { defineConfig } from 'vite';
import path from 'path';

export default defineConfig({
    // 根目录
    root: './src',
    
    // 公共基础路径
    base: '/',
    
    // 开发服务器配置
    server: {
        host: '0.0.0.0',
        port: 3000,
        open: true,
        https: false,
        cors: true,
        proxy: {
            '/api': {
                target: 'http://localhost:8080',
                changeOrigin: true,
                rewrite: (path) =&gt; path.replace(/^\/api/, '')
            }
        }
    },
    
    // 构建配置
    build: {
        outDir: '../dist',
        assetsDir: 'assets',
        sourcemap: true,
        minify: 'terser', // 'terser' | 'esbuild' | false
        rollupOptions: {
            output: {
                manualChunks: {
                    vendor: ['vue', 'vue-router'],
                    utils: ['lodash', 'axios']
                }
            }
        }
    },
    
    // 路径别名
    resolve: {
        alias: {
            '@': path.resolve(__dirname, './src'),
            'components': path.resolve(__dirname, './src/components')
        }
    },
    
    // CSS配置
    css: {
        modules: {
            localsConvention: 'camelCase'
        },
        preprocessorOptions: {
            scss: {
                additionalData: `@import "@/styles/variables.scss";`
            }
        }
    },
    
    // 插件
    plugins: [
        // Vue插件
        // vue(),
        
        // React插件
        // react()
    ]
});
                </pre>
            </div>
        </div>
        
        <h2>环境变量</h2>
        
        <div class="vite-demo">
            <h3>环境变量配置</h3>
            <div class="code-block">
                <pre>
# .env文件
VITE_APP_TITLE=我的应用
VITE_API_URL=http://localhost:3000/api

# .env.development
VITE_MODE=development
VITE_API_URL=http://dev.example.com/api

# .env.production
VITE_MODE=production
VITE_API_URL=https://api.example.com

// 使用环境变量
console.log(import.meta.env.VITE_APP_TITLE);
console.log(import.meta.env.VITE_API_URL);
console.log(import.meta.env.MODE);
console.log(import.meta.env.DEV);
console.log(import.meta.env.PROD);

// 类型定义(vite-env.d.ts)
/// &lt;reference types="vite/client" /&gt;

interface ImportMetaEnv {
    readonly VITE_APP_TITLE: string;
    readonly VITE_API_URL: string;
    readonly MODE: string;
    readonly DEV: boolean;
    readonly PROD: boolean;
}

interface ImportMeta {
    readonly env: ImportMetaEnv;
}
                </pre>
            </div>
        </div>
        
        <h2>构建和部署</h2>
        
        <div class="vite-demo">
            <h3>构建命令</h3>
            <div class="code-block">
                <pre>
{
    "scripts": {
        "dev": "vite",
        "build": "vite build",
        "preview": "vite preview",
        "serve": "vite preview --port 5000"
    }
}

# 开发模式
npm run dev

# 生产构建
npm run build

# 预览构建结果
npm run preview

# 部署到静态服务器
# 将dist目录上传到服务器即可
                </pre>
            </div>
        </div>
        
        <div style="background: #fff3cd; padding: 15px; border-radius: 5px; margin-top: 20px;">
            <strong>东巴文提示:</strong>Vite是新一代构建工具,开发体验极佳。适合新项目,特别是Vue和React应用。配置简单,性能优秀,是现代前端开发的推荐选择。
        </div>
    </div>
</body>
</html>

学习检验

完成本章学习后,请尝试回答以下问题:

  1. 选择题: 以下哪个构建工具的启动速度最快?

    • A. Webpack
    • B. Vite
    • C. Rollup
    • D. Parcel
  2. 填空题: Webpack中用于处理CSS文件的Loader是____和____。

  3. 简答题: 构建工具的主要作用有哪些?

  4. 实践题: 使用Vite创建一个原生JavaScript项目,完成以下操作:

    • 创建项目
    • 配置开发服务器
    • 添加CSS样式
    • 运行开发服务器
  5. 应用题: 比较Webpack和Vite的优缺点,为不同类型的项目选择合适的构建工具。