JavaScript系列(86)--现代构建工具详解

news2025/2/25 13:33:26

JavaScript 现代构建工具详解 🔨

现代前端开发离不开构建工具,它们帮助我们处理模块打包、代码转换、资源优化等任务。让我们深入了解主流的构建工具及其应用。

构建工具概述 🌟

💡 小知识:构建工具主要解决代码转换、文件优化、模块打包、自动刷新、代码分割等问题。主流的构建工具包括webpack、Vite、Rollup等,它们各有特点和适用场景。

webpack 详解 📦

// 1. webpack配置
class WebpackConfig {
    constructor() {
        this.config = {
            entry: './src/index.js',
            output: {
                path: path.resolve(__dirname, 'dist'),
                filename: '[name].[contenthash].js'
            },
            module: {
                rules: []
            },
            plugins: [],
            optimization: {
                splitChunks: {
                    chunks: 'all'
                }
            }
        };
    }
    
    addLoader(rule) {
        this.config.module.rules.push(rule);
    }
    
    addPlugin(plugin) {
        this.config.plugins.push(plugin);
    }
    
    setDevServer() {
        this.config.devServer = {
            contentBase: './dist',
            hot: true,
            port: 3000,
            compress: true,
            historyApiFallback: true
        };
    }
    
    setOptimization() {
        this.config.optimization = {
            minimize: true,
            minimizer: [
                new TerserPlugin(),
                new CssMinimizerPlugin()
            ],
            splitChunks: {
                chunks: 'all',
                minSize: 20000,
                maxSize: 244000,
                cacheGroups: {
                    vendor: {
                        test: /[\\/]node_modules[\\/]/,
                        name: 'vendors',
                        chunks: 'all'
                    }
                }
            }
        };
    }
}

// 2. 加载器配置
class LoaderConfig {
    static getJavaScriptLoader() {
        return {
            test: /\.(js|jsx|ts|tsx)$/,
            exclude: /node_modules/,
            use: {
                loader: 'babel-loader',
                options: {
                    presets: [
                        '@babel/preset-env',
                        '@babel/preset-react',
                        '@babel/preset-typescript'
                    ],
                    plugins: [
                        '@babel/plugin-transform-runtime'
                    ]
                }
            }
        };
    }
    
    static getStyleLoader() {
        return {
            test: /\.(css|scss)$/,
            use: [
                MiniCssExtractPlugin.loader,
                {
                    loader: 'css-loader',
                    options: {
                        modules: true,
                        importLoaders: 1
                    }
                },
                'postcss-loader',
                'sass-loader'
            ]
        };
    }
    
    static getAssetLoader() {
        return {
            test: /\.(png|svg|jpg|jpeg|gif)$/i,
            type: 'asset',
            parser: {
                dataUrlCondition: {
                    maxSize: 8 * 1024 // 8kb
                }
            }
        };
    }
}

// 3. 插件配置
class PluginConfig {
    static getCommonPlugins() {
        return [
            new HtmlWebpackPlugin({
                template: './src/index.html',
                filename: 'index.html',
                inject: 'body'
            }),
            new MiniCssExtractPlugin({
                filename: '[name].[contenthash].css'
            }),
            new CleanWebpackPlugin(),
            new webpack.DefinePlugin({
                'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
            })
        ];
    }
    
    static getAnalyzerPlugin() {
        return new BundleAnalyzerPlugin({
            analyzerMode: 'static',
            reportFilename: 'bundle-report.html'
        });
    }
    
    static getCompressionPlugin() {
        return new CompressionPlugin({
            algorithm: 'gzip',
            test: /\.(js|css|html|svg)$/,
            threshold: 10240,
            minRatio: 0.8
        });
    }
}

Vite 特性与应用 ⚡

// 1. Vite配置
class ViteConfig {
    static getBaseConfig() {
        return {
            root: process.cwd(),
            base: '/',
            mode: 'development',
            define: {
                __APP_VERSION__: JSON.stringify('1.0.0')
            },
            resolve: {
                alias: {
                    '@': '/src'
                }
            },
            css: {
                modules: {
                    localsConvention: 'camelCase'
                },
                preprocessorOptions: {
                    scss: {
                        additionalData: `@import "@/styles/variables.scss";`
                    }
                }
            }
        };
    }
    
    static getPlugins() {
        return [
            vue(),
            vueJsx(),
            legacy({
                targets: ['defaults', 'not IE 11']
            })
        ];
    }
    
    static getBuildConfig() {
        return {
            target: 'es2015',
            outDir: 'dist',
            assetsDir: 'assets',
            cssCodeSplit: true,
            sourcemap: false,
            rollupOptions: {
                output: {
                    manualChunks: {
                        vendor: ['vue', 'vue-router', 'vuex']
                    }
                }
            }
        };
    }
}

// 2. 开发服务器
class DevServer {
    constructor(config = {}) {
        this.config = {
            host: 'localhost',
            port: 3000,
            https: false,
            open: true,
            cors: true,
            ...config
        };
    }
    
    async start() {
        const server = await createServer({
            ...ViteConfig.getBaseConfig(),
            server: this.config
        });
        
        await server.listen();
        
        server.printUrls();
    }
    
    configureProxy() {
        return {
            '/api': {
                target: 'http://localhost:8080',
                changeOrigin: true,
                rewrite: path => path.replace(/^\/api/, '')
            }
        };
    }
}

// 3. 优化策略
class ViteOptimization {
    static getDependencyOptimization() {
        return {
            optimizeDeps: {
                include: [
                    'vue',
                    'vue-router',
                    '@vueuse/core'
                ],
                exclude: [
                    'vue-demi'
                ]
            }
        };
    }
    
    static getBuildOptimization() {
        return {
            build: {
                target: 'es2015',
                minify: 'terser',
                terserOptions: {
                    compress: {
                        drop_console: true,
                        drop_debugger: true
                    }
                },
                rollupOptions: {
                    output: {
                        manualChunks(id) {
                            if (id.includes('node_modules')) {
                                return 'vendor';
                            }
                        }
                    }
                }
            }
        };
    }
}

Rollup 配置与插件 📦

// 1. Rollup配置
class RollupConfig {
    static getBaseConfig() {
        return {
            input: 'src/index.js',
            output: [
                {
                    file: 'dist/bundle.cjs.js',
                    format: 'cjs'
                },
                {
                    file: 'dist/bundle.esm.js',
                    format: 'es'
                },
                {
                    file: 'dist/bundle.umd.js',
                    format: 'umd',
                    name: 'MyLibrary'
                }
            ],
            plugins: [],
            external: ['react', 'react-dom']
        };
    }
    
    static getPlugins() {
        return [
            resolve({
                browser: true
            }),
            commonjs(),
            babel({
                babelHelpers: 'bundled',
                exclude: 'node_modules/**'
            }),
            terser()
        ];
    }
    
    static getWatchConfig() {
        return {
            watch: {
                include: 'src/**',
                exclude: 'node_modules/**'
            }
        };
    }
}

// 2. 插件开发
class RollupPlugin {
    static createPlugin(options = {}) {
        return {
            name: 'my-rollup-plugin',
            
            buildStart() {
                console.log('Build starting...');
            },
            
            resolveId(source, importer) {
                if (source === 'virtual-module') {
                    return source;
                }
                return null;
            },
            
            load(id) {
                if (id === 'virtual-module') {
                    return 'export default "This is virtual!"';
                }
                return null;
            },
            
            transform(code, id) {
                if (id.includes('.js')) {
                    // 转换代码
                    return {
                        code: code,
                        map: null
                    };
                }
            }
        };
    }
}

// 3. 构建优化
class RollupOptimization {
    static getTerserConfig() {
        return {
            compress: {
                dead_code: true,
                drop_console: true,
                drop_debugger: true,
                pure_getters: true,
                unsafe: true,
                unsafe_comps: true
            },
            mangle: {
                properties: {
                    regex: /^_/
                }
            }
        };
    }
    
    static getTreeShakingConfig() {
        return {
            treeshake: {
                moduleSideEffects: false,
                propertyReadSideEffects: false,
                tryCatchDeoptimization: false
            }
        };
    }
}

性能优化策略 ⚡

// 1. 代码分割
class CodeSplitting {
    static getWebpackConfig() {
        return {
            optimization: {
                splitChunks: {
                    chunks: 'all',
                    minSize: 20000,
                    maxSize: 244000,
                    cacheGroups: {
                        vendor: {
                            test: /[\\/]node_modules[\\/]/,
                            name(module) {
                                const packageName = module.context.match(
                                    /[\\/]node_modules[\\/](.*?)([\\/]|$)/
                                )[1];
                                return `vendor.${packageName.replace('@', '')}`;
                            }
                        },
                        common: {
                            name: 'common',
                            minChunks: 2,
                            priority: -20
                        }
                    }
                }
            }
        };
    }
    
    static getViteConfig() {
        return {
            build: {
                rollupOptions: {
                    output: {
                        manualChunks: {
                            vendor: ['vue', 'vue-router', 'vuex'],
                            utils: ['lodash-es', 'axios']
                        }
                    }
                }
            }
        };
    }
}

// 2. 缓存优化
class CacheOptimization {
    static getWebpackCacheConfig() {
        return {
            cache: {
                type: 'filesystem',
                buildDependencies: {
                    config: [__filename]
                },
                name: 'production-cache'
            },
            output: {
                filename: '[name].[contenthash].js',
                chunkFilename: '[name].[contenthash].chunk.js'
            }
        };
    }
    
    static getViteCacheConfig() {
        return {
            optimizeDeps: {
                entries: ['src/**/*.{vue,js,ts}'],
                include: ['vue', 'vue-router'],
                exclude: ['your-unstable-package']
            },
            build: {
                commonjsOptions: {
                    include: [/node_modules/]
                }
            }
        };
    }
}

// 3. 资源优化
class AssetOptimization {
    static getImageOptimization() {
        return {
            test: /\.(png|jpg|gif|svg)$/i,
            use: [
                {
                    loader: 'image-webpack-loader',
                    options: {
                        mozjpeg: {
                            progressive: true,
                            quality: 65
                        },
                        optipng: {
                            enabled: false
                        },
                        pngquant: {
                            quality: [0.65, 0.90],
                            speed: 4
                        },
                        gifsicle: {
                            interlaced: false
                        },
                        webp: {
                            quality: 75
                        }
                    }
                }
            ]
        };
    }
    
    static getCSSOptimization() {
        return {
            test: /\.css$/,
            use: [
                MiniCssExtractPlugin.loader,
                {
                    loader: 'css-loader',
                    options: {
                        modules: true,
                        importLoaders: 1
                    }
                },
                {
                    loader: 'postcss-loader',
                    options: {
                        postcssOptions: {
                            plugins: [
                                'postcss-preset-env',
                                'cssnano'
                            ]
                        }
                    }
                }
            ]
        };
    }
}

构建分析与监控 📊

// 1. 构建分析
class BuildAnalyzer {
    static getWebpackAnalyzer() {
        return new BundleAnalyzerPlugin({
            analyzerMode: 'static',
            reportFilename: 'bundle-report.html',
            openAnalyzer: false,
            generateStatsFile: true,
            statsFilename: 'bundle-stats.json'
        });
    }
    
    static getStatsConfig() {
        return {
            stats: {
                assets: true,
                chunks: true,
                modules: false,
                children: false,
                performance: true,
                timings: true,
                hash: false,
                version: false,
                builtAt: false,
                entrypoints: false
            }
        };
    }
    
    static analyzeBuildResult(stats) {
        return {
            totalSize: this.calculateTotalSize(stats),
            chunks: this.analyzeChunks(stats),
            assets: this.analyzeAssets(stats),
            performance: this.analyzePerformance(stats)
        };
    }
}

// 2. 性能监控
class PerformanceMonitor {
    constructor() {
        this.metrics = {
            buildTime: 0,
            chunkCount: 0,
            totalSize: 0,
            warnings: []
        };
    }
    
    startBuild() {
        this.buildStartTime = Date.now();
    }
    
    endBuild() {
        this.metrics.buildTime = Date.now() - this.buildStartTime;
    }
    
    collectMetrics(stats) {
        this.metrics.chunkCount = stats.chunks.length;
        this.metrics.totalSize = this.calculateTotalSize(stats);
        this.metrics.warnings = stats.warnings;
    }
    
    generateReport() {
        return {
            ...this.metrics,
            timestamp: new Date().toISOString(),
            performance: this.evaluatePerformance()
        };
    }
}

// 3. 错误处理
class BuildErrorHandler {
    static handleError(error) {
        console.error('Build Error:', error);
        
        if (error.name === 'ModuleBuildError') {
            this.handleModuleError(error);
        } else if (error.name === 'ChunkRenderError') {
            this.handleChunkError(error);
        } else {
            this.handleGenericError(error);
        }
    }
    
    static generateErrorReport(errors) {
        return {
            count: errors.length,
            details: errors.map(error => ({
                type: error.name,
                message: error.message,
                module: error.module?.resource,
                stack: error.stack
            }))
        };
    }
    
    static notifyError(error) {
        // 实现错误通知逻辑
    }
}

结语 📝

现代构建工具为前端开发提供了强大的工程化能力。我们学习了:

  1. webpack的配置和优化
  2. Vite的特性和应用
  3. Rollup的插件开发
  4. 性能优化策略
  5. 构建分析与监控
  6. 错误处理机制

💡 学习建议:

  1. 深入理解不同构建工具的特点
  2. 掌握性能优化的关键点
  3. 重视构建配置的可维护性
  4. 建立完善的监控机制
  5. 持续优化构建流程

如果你觉得这篇文章有帮助,欢迎点赞收藏,也期待在评论区看到你的想法和建议!👇

终身学习,共同成长。

咱们下一期见

💻

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/2304907.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

使用Windbg调试目标进程排查C++软件异常的一般步骤与要点分享

目录 1、概述 2、将Windbg附加到已经启动起来的目标进程上,或者用Windbg启动目标程序 2.1、将Windbg附加到已经启动起来的目标进程上 2.2、用Windbg启动目标程序 2.3、Windbg关联到目标进程上会中断下来,输入g命令将该中断跳过去 3、分析实例说明 …

ddd 文章总结分享,ddd实战代码分享, 领域驱动设计java实战源码大全,我看过的ddd java源码

1. 前段时间研究ddd, 收藏了很多相关知识,分享出来,希望能够帮助更多的小伙伴了解ddd, 什么是领域驱动设计,并分享在github发现的开源ddd代码 2. ddd 必须强烈点赞阿里两位大佬,一个为殷浩, 一个为cola作者 2.1.1 殷浩…

什么是MySql的主从复制(主从同步)?

主页还有其他面试题总结,有需要的可以去看一下,喜欢的就留个三连再走吧~ 1.什么是MySql的主从复制原理? 主从复制的核心就是二进制binlog(DDL(数据定义语言)语句和DML(数据操纵语言&#xff09…

蓝桥云课python代码

第一章语言基础 第一节编程基础 1 python开发环境 第一个Python程序 # 打印"Hello World" print("Hello World")# 打印2的100次方 print(2 ** 100)# 打印112 print("11",1 1)""" Hello World 126765060022822940149670320537…

c#丰田PLC ToyoPuc TCP协议快速读写 to c# Toyota PLC ToyoPuc读写

源代码下载 <------下载地址 历史背景与发展 TOYOPUC协议源于丰田工机&#xff08;TOYODA&#xff09;的自动化技术积累。丰田工机成立于1941年&#xff0c;最初是丰田汽车的机床部门&#xff0c;后独立为专注于工业机械与控制系统的公司。2006年与光洋精工&#xff08;Ko…

深入解析-无状态服务-StatefulSet (一)

一、有状态服务 VS 无状态服务 1.无状态服务介绍 1.数据方面&#xff1a;无状态服务不会在本地存储持久化数据.多个实例可以共享相同的持久化数据 2.结果方面&#xff1a;多个服务实例对于同一个用户请求的响应结果是完全一致的 3.关系方面&#xff1a;这种多服务实例之间是…

hackmyvm-buster

题目地址 信息收集 主机发现 ┌──(root㉿kali)-[/home/kali] └─# arp-scan -I eth1 192.168.56.0/24 Interface: eth1, type: EN10MB, MAC: 00:0c:29:34:da:f5, IPv4: 192.168.56.103 WARNING: Cannot open MAC/Vendor file ieee-oui.txt: Permission denied WARNING: C…

【原创】Windows11安装WSL“无法解析服务器的名称或地址”问题解决方法

原因分析 出现这个问题一开始以为WSL设置了某个服务器&#xff0c;但是通过运行 nslookup www.microsoft.com 出现下面的提示 PS C:\Windows\system32> nslookup www.microsoft.com 服务器: UnKnown Address: 2408:8000:XXXX:2b00:8:8:8:8非权威应答: 名称: e13678…

网页制作08-html,css,javascript初认识のhtml使用框架结构,请先建立站点!

框架一般由框架集和框架组成。 框架集就像一个大的容器&#xff0c;包括所有的框架&#xff0c;是框架的集合。 框架是框架集中一个独立的区域用于显示一个独立的网页文档。 框架集是文件html&#xff0c;它定义一组框架的布局和属性&#xff0c;包括框架的数目&#xff0c;框架…

【Vscode 使用】集合1

一、使用make工具管理工程 windows下&#xff0c;下载mingw64&#xff0c;配置好mingw64\bin 为 Win10系统全局变量后。 在mingw64/bin目录下找到mingw32-make.exe工具。复制一份改名为&#xff1a;make.exe&#xff0c;没错&#xff0c;就是那么简单&#xff0c;mingw64自带m…

文章精读篇——用于遥感小样本语义分割的可学习Prompt

题目&#xff1a;Learnable Prompt for Few-Shot Semantic Segmentation in Remote Sensing Domain 会议&#xff1a;CVPR 2024 Workshop 论文&#xff1a;10.48550/arXiv.2404.10307 相关竞赛&#xff1a;https://codalab.lisn.upsaclay.fr/competitions/17568 年份&#…

解决 kubeasz 安装k8s集群跨节点pod 无法使用cluster ip通讯问题

问题描述 使用kubeasz搭建k8s集群后使用的配置文件 # etcd cluster should have odd member(s) (1,3,5,...) [etcd] 192.168.xx.22# master node(s) [kube_master] 192.168.xx.22# work node(s) [kube_node] 192.168.xx.9 192.168.xx.22# [optional] harbor server, a privat…

Docker 搭建 Nginx 服务器

系列文章目录 Docker 搭建 Nginx 服务器 系列文章目录前言一、准备工作二、设置 Nginx 容器的目录结构三、启动一个临时的 Nginx 容器来复制配置文件四、复制 Nginx 配置文件到本地目录五、删除临时 Nginx 容器六、创建并运行 Nginx 容器&#xff0c;挂载本地目录七、修改 ngin…

Spring AI + 大模型开发应用

JAVA SpringAI 大模型开发AI应用DEMO 前言JAVA项目创建示例 前言 在当今快速发展的技术领域&#xff0c;人工智能&#xff08;AI&#xff09;已经成为推动创新和变革的重要力量。然而&#xff0c;AI应用的开发过程往往复杂且耗时&#xff0c;需要开发者具备深厚的技术背景和丰…

【C++11】 并发⽀持库

&#x1f308; 个人主页&#xff1a;Zfox_ &#x1f525; 系列专栏&#xff1a;C从入门到精通 目录 前言&#xff1a;&#x1f680; 并发⽀持库一&#xff1a;&#x1f525; thread库 二&#xff1a;&#x1f525; this_thread 三&#xff1a;&#x1f525; mutex 四&#xff1…

Windows 11【1001问】如何下载Windows 11系统镜像

随着科技的不断进步&#xff0c;操作系统也在不断地更新换代。Windows 11作为微软最新一代的操作系统&#xff0c;带来了许多令人兴奋的新特性与改进&#xff0c;如全新的用户界面、更好的性能优化以及增强的安全功能等。对于想要体验最新技术或者提升工作效率的用户来说&#…

视觉分析之边缘检测算法

9.1 Roberts算子 Roberts算子又称为交叉微分算法&#xff0c;是基于交叉差分的梯度算法&#xff0c;通过局部差分计算检测边缘线条。 常用来处理具有陡峭的低噪声图像&#xff0c;当图像边缘接近于正45度或负45度时&#xff0c;该算法处理效果更理想。 其缺点是对边缘的定位…

深度学习-6.用于计算机视觉的深度学习

Deep Learning - Lecture 6 Deep Learning for Computer Vision 简介深度学习在计算机视觉领域的发展时间线 语义分割语义分割系统的类型上采样层语义分割的 SegNet 架构软件中的SegNet 架构数据标注 目标检测与识别目标检测与识别问题两阶段和一阶段目标检测与识别两阶段检测器…

【大模型】蓝耘智算云平台快速部署DeepSeek R1/R3大模型详解

目录 一、前言 二、蓝耘智算平台介绍 2.1 蓝耘智算平台是什么 2.2 平台优势 2.3 应用场景 2.4 对DeepSeek 的支持 2.4.1 DeepSeek 简介 2.4.2 DeepSeek 优势 三、蓝耘智算平台部署DeepSeek-R1操作过程 3.1 注册账号 3.1.1 余额检查 3.2 部署DeepSeek-R1 3.2.1 获取…

《计算机视觉》——图像拼接

图像拼接 图像拼接是将多幅有重叠区域的图像合并成一幅全景或更大视角图像的技术&#xff0c;以下为你详细介绍&#xff1a; 原理&#xff1a;图像拼接的核心原理是基于图像之间的特征匹配。首先&#xff0c;从每幅图像中提取独特的特征点&#xff0c;如角点、边缘点等&#x…