对线面试官☞谈谈对Vue.config.js 文件的理解

68 阅读1分钟

vue.config.js 是 Vue CLI 项目中的配置文件,它允许你自定义构建、开发服务器等行为。这个文件通常位于项目的根目录下。以下是一些常见的配置选项:

  1. 基本配置

    module.exports = {
      outputDir: 'dist', // 构建输出目录
      assetsDir: 'static', // 静态资源目录 (js, css, img, fonts)
      runtimeCompiler: true, // 启用包含运行时编译器的 Vue 构建
      productionSourceMap: false, // 是否在生产环境下生成 source map
      parallel: require('os').cpus().length, // 构建过程中 workers 线程数
    };
    
  2. 开发服务器配置

    module.exports = {
      devServer: {
        host: '0.0.0.0', // 绑定的主机地址
        port: 8080, // 端口号
        open: true, // 启动时自动打开浏览器
        https: false, // 是否使用 HTTPS
        proxy: {
          '/api': { // 代理配置
            target: 'http://example.com',
            changeOrigin: true,
            pathRewrite: {'^/api' : ''}
          }
        },
        before: app => { /* 服务器启动前的钩子 */ }
      }
    };
    
  3. 插件和加载器配置

    module.exports = {
      chainWebpack: config => {
        // 查找是否存在 'vue' 规则并修改它的 loader
        config.module
          .rule('vue')
          .use('vue-loader')
          .tap(options => {
            // 修改 `vue-loader` 的选项
            return {
              ...options,
              compilerOptions: {
                // 在这里添加选项
              }
            };
          });
      },
      pluginOptions: {
        // 插件选项
      }
    };
    
  4. 环境变量

    const path = require('path');
    
    module.exports = {
      configureWebpack: {
        plugins: [
          // 你的插件配置
        ]
      },
      chainWebpack: config => {
        config.plugin('provide').tap(args => {
          args[0].jquery = 'jquery';
          return args;
        });
        // 其他链式操作
      },
      pluginOptions: {
        // 插件选项
      },
      // 环境变量
      transpileDependencies: [
        /* string 或 RegExp */
      ]
    };
    
  5. 第三方插件配置

    module.exports = {
      pluginOptions: {
        'style-resources-loader': {
          preProcessor: 'scss',
          patterns: [
            // 你的样式文件路径
          ]
        }
      }
    };
    
  6. 多页面应用配置

    module.exports = {
      pages: {
        index: {
          // page 的入口
          entry: 'src/index/main.js',
          // 模板来源
          template: 'public/index.html',
          // 输出文件名 (相对于 outputDir)
          filename: 'index.html',
          // 当使用 title 选项时
          title: 'Index Page',
          // 在这个页面中包含的块,默认情况下会包含
          // 提取出来的 common chunk 和 vendor chunk
          chunks: ['chunk-vendors', 'chunk-common', 'index']
        },
        // 其他页面配置...
      }
    };