回答于 2025-04-01
markdown
Pro 配置文件中 JavaScript 常用配置项
以下是常见的 JavaScript 配置文件(如 webpack.config.js/vite.config.js 等)中高频使用的配置项:
1. 基础配置
javascript module.exports = { // 入口文件配置 entry: './src/index.js',
// 输出配置 output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.[contenthash].js', clean: true // 构建前清理旧文件 },
// 开发模式/生产模式 mode: 'production' // 可选 'development' | 'production' };
2. 代码优化
javascript // Webpack 示例 optimization: { minimize: true, // 启用代码压缩 minimizer: [new TerserPlugin()], // 使用 Terser 压缩 JS splitChunks: { // 代码分割 chunks: 'all', cacheGroups: { vendor: { test: /[\/]node_modules[\/]/, name: 'vendors' } } } }
3. 资源处理
javascript module: { rules: [ // Babel 转译 ES6+ 代码 { test: /.js$/, exclude: /node_modules/, use: { loader: 'babel-loader', options: { presets: ['@babel/preset-env'] } } }, // 静态资源处理 { test: /.(png|svg|jpg|gif)$/, type: 'asset/resource' } ] }
4. 开发调试
javascript // Source Map 配置(生产环境建议关闭) devtool: 'source-map',
// 开发服务器配置 devServer: { static: './dist', hot: true, // 热更新 port: 3000, open: true }
5. 插件扩展
javascript plugins: [ // 生成 HTML 入口文件 new HtmlWebpackPlugin({ template: './public/index.html' }),
// 压缩 CSS new CssMinimizerPlugin(),
// 打包分析工具 new BundleAnalyzerPlugin() ]
6. 环境变量
javascript // 通过 dotenv 加载 .env 文件 require('dotenv').config();
// 注入环境变量 const env = { API_URL: JSON.stringify(process.env.API_URL) };
// 在配置中使用 plugins: [ new webpack.DefinePlugin({ 'process.env': env }) ]
常用工具链配置
| 工具 | 配置文件 | 核心功能 |
|-------------|----------------------|--------------------------|
| Webpack | webpack.config.js | 模块打包/代码分割 |
| Vite | vite.config.js | 极速开发/按需编译 |
| Babel | .babelrc | ES6+ 转译 |
| ESLint | .eslintrc.js | 代码规范检查 |
| TypeScript | tsconfig.json | TS 类型检查/编译配置 |
提示:具体配置需根据项目框架(如 React/Vue)和构建工具调整,建议参考官方文档。