构建工具配置
工程化规范的必要性
现代前端项目复杂度不断提升,代码量呈指数级增长。工程化规范成为团队协作和项目维护的基础保障,它能有效解决代码风格混乱、依赖管理困难、构建效率低下等问题。统一的规范让不同开发者编写的代码具有一致性,降低沟通成本,提高代码可维护性。
代码规范工具配置
ESLint 配置示例
ESLint 是目前最流行的 JavaScript 代码检查工具。通过配置文件 .eslintrc.js
可以定义团队统一的代码风格:
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 集成
Prettier 作为代码格式化工具,可以与 ESLint 配合使用。.prettierrc
配置示例:
{
"printWidth": 80,
"tabWidth": 2,
"useTabs": false,
"semi": true,
"singleQuote": true,
"trailingComma": "es5"
}
在 package.json
中添加格式化脚本:
{
"scripts": {
"format": "prettier --write \"src/**/*.{js,ts,jsx,tsx}\""
}
}
构建工具基础配置
Webpack 核心配置
Webpack 是现代前端项目最常用的构建工具之一。基础配置文件 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 转译配置
对于需要兼容旧版浏览器的项目,Babel 配置 .babelrc
:
{
"presets": [
["@babel/preset-env", {
"targets": {
"chrome": "58",
"ie": "11"
},
"useBuiltIns": "usage",
"corejs": "3.26"
}],
"@babel/preset-typescript"
],
"plugins": [
"@babel/plugin-transform-runtime"
]
}
高级构建优化
代码分割策略
Webpack 的代码分割可以显著提升应用加载性能:
// webpack.config.js
module.exports = {
//...
optimization: {
splitChunks: {
chunks: 'all',
cacheGroups: {
vendor: {
test: /[\\/]node_modules[\\/]/,
name: 'vendors',
chunks: 'all'
}
}
}
}
};
Tree Shaking 配置
对于 ES Module 的项目,启用 tree shaking 消除未使用代码:
// webpack.config.js
module.exports = {
//...
optimization: {
usedExports: true,
minimize: true,
minimizer: [
new TerserPlugin({
terserOptions: {
compress: {
drop_console: true
}
}
})
]
}
};
环境变量管理
多环境配置方案
通过 webpack-merge
实现不同环境配置:
// webpack.common.js
const { merge } = require('webpack-merge');
const commonConfig = {
// 公共配置
};
module.exports = (env) => {
const envConfig = require(`./webpack.${env.NODE_ENV}.js`);
return merge(commonConfig, envConfig);
};
对应环境配置文件示例 webpack.prod.js
:
const CssMinimizerPlugin = require('css-minimizer-webpack-plugin');
module.exports = {
mode: 'production',
devtool: 'source-map',
optimization: {
minimizer: [
new CssMinimizerPlugin()
]
}
};
自定义 Loader 和 Plugin
开发简单 Loader
示例:创建一个替换字符串的 loader:
// replace-loader.js
module.exports = function(source) {
return source.replace(/Hello/g, 'Hi');
};
在 Webpack 配置中使用:
module.exports = {
//...
module: {
rules: [
{
test: /\.txt$/,
use: [
{
loader: path.resolve(__dirname, 'replace-loader.js')
}
]
}
]
}
};
开发简单 Plugin
基础 Plugin 示例:
class LogPlugin {
apply(compiler) {
compiler.hooks.done.tap('LogPlugin', (stats) => {
console.log('编译完成:', stats.hash);
});
}
}
module.exports = {
plugins: [
new LogPlugin()
]
};
性能监控与分析
构建速度分析
使用 speed-measure-webpack-plugin
测量构建时间:
const SpeedMeasurePlugin = require('speed-measure-webpack-plugin');
const smp = new SpeedMeasurePlugin();
module.exports = smp.wrap({
// webpack配置
});
Bundle 分析工具
配置 webpack-bundle-analyzer
:
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
module.exports = {
plugins: [
new BundleAnalyzerPlugin({
analyzerMode: 'static',
reportFilename: 'bundle-report.html'
})
]
};
现代化构建方案
Vite 基础配置
Vite 的 vite.config.js
示例:
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 配置示例
Rollup 适合库开发,基础配置 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' })
]
};
持续集成中的构建优化
CI/CD 缓存策略
在 GitHub Actions 中缓存 node_modules 和构建产物的示例:
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
并行构建配置
利用 thread-loader
加速构建:
module.exports = {
module: {
rules: [
{
test: /\.js$/,
use: [
{
loader: 'thread-loader',
options: {
workers: 4
}
},
'babel-loader'
]
}
]
}
};
本站部分内容来自互联网,一切版权均归源网站或源作者所有。
如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn