Vue.config.js配置详解

Vue.config.js 是 Vue 项目中的配置文件,用于自定义构建设置。它包含各种配置选项,如公共路径、输出目录、静态资源处理等。在多页应用中,还可以配置每个页面的入口、模板等。此外,还能设置 ESLint 的校验规则,以及在开发和生产环境下的源码映射。通过 alias,可以为特定文件夹设置别名。函数形式的配置允许对 webpack 配置进行深度定制。若需在开发环境将 API 请求代理到另一服务器,可通过 devServer.proxy 配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

vue.config.js配置详解

简介

vue.config.js 是一个可选的配置文件,如果项目的 (和 package.json 同级的) 根目录中存在这个文件,那么它会被 @vue/cli-service 自动加载。你也可以使用 package.json 中的 vue 字段,但是注意这种写法需要你严格遵照 JSON 的格式来写。

这个文件应该导出一个包含了选项的对象:

// vue.config.js

/**
 * @type {import('@vue/cli-service').ProjectOptions}
 */
module.exports = {
  // 选项...
}

或者,你也可以使用 @vue/cli-service 提供的 defineConfig 帮手函数,以获得更好的类型提示:

// vue.config.js
const { defineConfig } = require('@vue/cli-service')

module.exports = defineConfig({
  // 选项
})

publicPath

  • Type:string
  • Default:/

由于在Vue CLI 3.3 之后baseUrl已被弃用,使用publicPath进行替代。

默认情况下,Vue CLI 会假设你的应用是被部署在一个域名的根路径上,例如 https://www.my-app.com/,此时publicPath的值为/如果应用被部署在一个子路径上,你就需要用这个选项指定这个子路径。例如,如果你的应用被部署在 https://www.my-app.com/my-app/,则设置 publicPath/my-app/

相对 publicPath 的限制

相对路径的 publicPath 有一些使用上的限制。在以下情况下,应当避免使用相对 publicPath:

  • 当使用基于 HTML5 history.pushState 的路由时;
  • 当使用 pages 选项构建多页面应用时。
module.exports = {
  publicPath: process.env.NODE_ENV === 'production' ? '/admin/' : '/'
}

outputDir

  • Type: string
  • Default: 'dist'

Vue的项目中当运行npm run build对项目进行生产环境打包时生成的文件夹通常命名为dist可以通过更改此配置来更改文件夹的名称

提示

请始终使用 outputDir 而不要修改 webpack 的 output.path

module.exports = {
  outputDir: 'dist'
}

assetsDir

  • Type: string

  • Default: ''

    放置生成的静态资源 (jscssimgfonts) 的 (相对于 outputDir 的) 目录。

提示

从生成的资源覆写 filenamechunkFilename 时,assetsDir 会被忽略。

module.exports = {
  assetsDir: 'static'
}

indexPath

  • Type: string

  • Default: 'index.html'

    指定生成的 index.html 的输出路径 (相对于 outputDir)。也可以是一个绝对路径。

module.exports = {
  assetsDir: 'index.html'
}

filenameHashing

  • Type: boolean

  • Default: true

    默认情况下,生成的静态资源在它们的文件名中包含了 hash 以便更好的控制缓存。然而,这也要求 index 的 HTML 是被 Vue CLI 自动生成的。如果你无法使用 Vue CLI 生成的 index HTML,你可以通过将这个选项设为 false 来关闭文件名哈希。

module.exports = {
  filenameHashing:false
}

pages

  • Type: Object

  • Default: undefined

    在 multi-page 模式下构建应用。每个“page”应该有一个对应的 JavaScript 入口文件。其值应该是一个对象,对象的 key 是入口的名字,value 是:

    • 一个指定了 entry, template, filename, titlechunks 的对象 (除了 entry 之外都是可选的);
    • 或一个指定其 entry 的字符串。
module.exports = {
  pages: {
    index: {
      // page 的入口
      entry: 'src/index/main.js',
      // 模板来源
      template: 'public/index.html',
      // 在 dist/index.html 的输出
      filename: 'index.html',
      // 当使用 title 选项时, 
      // template 中的 title 标签需要是 <title><%= htmlWebpackPlugin.options.title %></title>
      title: 'Index Page',
      // 在这个页面中包含的块,默认情况下会包含
      // 提取出来的通用 chunk 和 vendor chunk。
      chunks: ['chunk-vendors', 'chunk-common', 'index']
    },
    // 当使用只有入口的字符串格式时,
    // 模板会被推导为 `public/subpage.html`
    // 并且如果找不到的话,就回退到 `public/index.html`。
    // 输出文件名会被推导为 `subpage.html`。
    subpage: 'src/subpage/main.js'
  }
}

提示

当在 multi-page 模式下构建时,webpack 配置会包含不一样的插件 (这时会存在多个 html-webpack-pluginpreload-webpack-plugin 的实例)。如果你试图修改这些插件的选项,请确认运行 vue inspect

lintOnSave

  • Type: boolean | 'warning' | 'default' | 'error'
  • Default: 'default'

检验语法规范,只有当安装了@vue/cli-plugin-eslint之后才会生效。

设置为 true'warning' 时,eslint-loader 会将 lint 错误输出为编译警告。默认情况下,警告仅仅会被输出到命令行,且不会使得编译失败。

如果你希望让 lint 错误在开发时直接显示在浏览器中,你可以使用 lintOnSave: 'default'。这会强制 eslint-loader 将 lint 错误输出为编译错误,同时也意味着 lint 错误将会导致编译失败。

设置为 error 将会使得 eslint-loader 把 lint 警告也输出为编译错误,这意味着 lint 警告将会导致编译失败。

或者,你也可以通过设置让浏览器 overlay 同时显示警告和错误:

// vue.config.js
module.exports = {
  devServer: {
    overlay: {
      warnings: true,
      errors: true
    }
  }
}

lintOnSave 是一个 truthy 的值时,eslint-loader 在开发和生产构建下都会被启用。如果你想要在生产构建时禁用 eslint-loader,你可以用如下配置:

// vue.config.js
module.exports = {
  lintOnSave: process.env.NODE_ENV !== 'production'
}

runtimeCompiler

  • Type: boolean

  • Default: false

    是否使用包含运行时编译器的 Vue 构建版本。设置为 true 后你就可以在 Vue 组件中使用 template 选项了,但是这会让你的应用额外增加 10kb 左右。

transpileDependencies

  • Type: boolean | Array<string | RegExp>

  • Default: false

    默认情况下 babel-loader 会忽略所有 node_modules 中的文件。你可以启用本选项,以避免构建后的代码中出现未转译的第三方依赖。

    不过,对所有的依赖都进行转译可能会降低构建速度。如果对构建性能有所顾虑,你可以只转译部分特定的依赖:给本选项传一个数组,列出需要转译的第三方包包名或正则表达式即可。

// vue.config.js
module.exports = {
  transpileDependencies: [
    'vue-echarts',
    'resize-detector'
  ]
}

productionSourceMap

  • Type: boolean

  • Default: true

    如果你不需要生产环境的 source map,可以将其设置为 false 以加速生产环境构建。

crossorigin

  • Type: string

  • Default: undefined

    设置生成的 HTML 中 <link rel="stylesheet"><script> 标签的 crossorigin 属性。

    需要注意的是该选项仅影响由 html-webpack-plugin 在构建时注入的标签 - 直接写在模版 (public/index.html) 中的标签不受影响。

    更多细节可查阅: CORS settings attributes

configureWebpack

  • Type: Object | Function

    如果这个值是一个对象,则会通过 webpack-merge 合并到最终的配置中。

    如果这个值是一个函数,则会接收被解析的配置作为参数。该函数既可以修改配置并不返回任何东西,也可以返回一个被克隆或合并过的配置版本。

对象形式

configureWebpack:{
       resolve: {
           // 别名配置
            alias: {
              'assets': '@/assets',
              'common': '@/common',
              'components': '@/components',
              'network': '@/network',
              'configs': '@/configs',
              'views': '@/views',
              'plugins': '@/plugins',
             }
        }
    },

对象形式可以为某些特定文件夹区别名

也可以写成如下形式:

  configureWebpack: {
    //在webpack的name字段中提供应用的标题,这样就可以在index.html中访问它来注入正确的标题。
    name: name,
    resolve: {
      alias: {
        '@': resolve('src'),
        '@crud': resolve('src/components/Crud')
      }
    }
  },

函数形式

 configureWebpack:
        (config) => {
            if (process.env.NODE_ENV === 'production') {
                // 为生产环境修改配置...
                config.mode = 'production'
            } else {
                // 为生产环境修改配置...
                config.mode = 'development'
            }
            // 开发生产共同配置别名
            Object.assign(config.resolve, {
                    alias: {
                        '@': path.resolve(__dirname, './src'),
                        'assets': path.resolve(__dirname, './src/assets'),
                        'common': path.resolve(__dirname, './src/common'),
                        'components': path.resolve(__dirname, './src/components'),
                        'network': path.resolve(__dirname, './src/network'),
                        'configs': path.resolve(__dirname, './src/configs'),
                        'views': path.resolve(__dirname, './src/views'),
                        'plugins': path.resolve(__dirname, './src/plugins'),
                    }
            })
        },

chainWebpack

  • Type: Function

    是一个函数,会接收一个基于 webpack-chainChainableConfig 实例。允许对内部的 webpack 配置进行更细粒度的修改。

    chainWebpack:(config)=>{
		config.plugins.delete('preload'); // TODO: need test
		config.plugins.delete('prefetch'); // TODO: need test
		config.plugin('html').tap(args=>{
			args[0].title=name
			return args
		})

        config.resolve.alias
            .set('@',resolve('./src'))
            .set('components',resolve('./src/components'))
            .set('views',resolve('./src/views'))
            .set('assets',resolve('./src/assets'))
    }

或者

  chainWebpack(config) {
      
    //下面两行代码是移除preload(预载) 与 prefetch (预取)
    //vue 脚手架默认开启了 preload 与 prefetch,当我们项目很大时,这个就成了首屏加载的最大元凶了。
    //先简单了解一下 preload 与 prefetch。
      		//preload 与 prefetch 都是一种资源预加载机制;
      		//preload 是预先加载资源,但并不执行,只有需要时才执行它;
      		//prefetch 是意图预获取一些资源,以备下一个导航/页面使用;
      		//preload 的优先级高于 prefetch。
    config.plugins.delete('preload') // TODO: need test
    config.plugins.delete('prefetch') // TODO: need test

    // set svg-sprite-loader
    config.module
      .rule('svg')
      .exclude.add(resolve('src/assets/icons'))
      .end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/assets/icons'))
      .end()
      .use('svg-sprite-loader')
      .loader('svg-sprite-loader')
      .options({
        symbolId: 'icon-[name]'
      })
      .end()

    // set preserveWhitespace
    config.module
      .rule('vue')
      .use('vue-loader')
      .loader('vue-loader')
      .tap(options => {
        options.compilerOptions.preserveWhitespace = true
        return options
      })
      .end()

    config
      // https://webpack.js.org/configuration/devtool/#development
      .when(process.env.NODE_ENV === 'development',
        config => config.devtool('cheap-source-map')
      )

    config
      .when(process.env.NODE_ENV !== 'development',
        config => {
          config
            .plugin('ScriptExtHtmlWebpackPlugin')
            .after('html')
            .use('script-ext-html-webpack-plugin', [{
            // `runtime` must same as runtimeChunk name. default is `runtime`
              inline: /runtime\..*\.js$/
            }])
            .end()
          config
            .optimization.splitChunks({
              chunks: 'all',
              cacheGroups: {
                libs: {
                  name: 'chunk-libs',
                  test: /[\\/]node_modules[\\/]/,
                  priority: 10,
                  chunks: 'initial' // only package third parties that are initially dependent
                },
                elementUI: {
                  name: 'chunk-elementUI', // split elementUI into a single package
                  priority: 20, // the weight needs to be larger than libs and app or it will be packaged into libs or app
                  test: /[\\/]node_modules[\\/]_?element-ui(.*)/ // in order to adapt to cnpm
                },
                commons: {
                  name: 'chunk-commons',
                  test: resolve('src/components'), // can customize your rules
                  minChunks: 3, //  minimum common number
                  priority: 5,
                  reuseExistingChunk: true
                }
              }
            })
          config.optimization.runtimeChunk('single')
        }
      )
  },

devServer

  • Type: Object

    所有 webpack-dev-server 的选项都支持。注意:

    • 有些值像 hostporthttps 可能会被命令行参数覆写。
    • 有些值像 publicPathhistoryApiFallback 不应该被修改,因为它们需要和开发服务器的 publicPath 同步以保障正常的工作。
devServer: {
    // host: 'localhost',
    port: 8090, //项目运行的端口号
    open: true, //配置自动启动浏览器
}

devServer.proxy

  • Type: string | Object

    如果你的前端应用和后端 API 服务器没有运行在同一个主机上,你需要在开发环境下将 API 请求代理到 API 服务器。这个问题可以通过 vue.config.js 中的 devServer.proxy 选项来配置。

    devServer.proxy 可以是一个指向开发环境 API 服务器的字符串:

devServer: {
    // host: 'localhost',
    port: 8090, //项目运行的端口号
    open: true, //配置自动启动浏览器
    proxy: {
      "/opAdmin": {
        target: "http://116.66.65.193:8081", //对应服务端的接口地址
        changeOrigin: true, // 开启跨域
        pathRewrite: {
          "^/opAdmin": "/opAdmin" //将以 /opAdmin 开头的接口重写http://116.66.65.193:8081/opAdmin ,调用时直接以 /opAdmin开头即表示调用http://116.66.65.193:8081/opAdmin
          // "^/opAdmin": "/" //将以 /opAdmin 开头的接口重写http://116.66.65.193:8081/ ,调用时直接以 /opAdmin开头即表示调用http://116.66.65.193:8081/
          // "^/opAdmin": "" //将以 /opAdmin 开头的接口重写http://116.66.65.193:8081 ,调用时直接以 /opAdmin开头即表示调用http://116.66.65.193:8081
        }
      },
      "/DoorStatus": {
        target: "http://47.99.11.102:8088", //对应服务端的接口地址
        changeOrigin: true
      }
    }
  }
引用和引用[2]提供了关于vue.config.js配置的详细介绍和示例代码。vue.config.js是一个用于配置Vue项目的文件,主要用于修改Webpack的配置和其他一些项目设置。在这个文件中,你可以设置诸如webpack配置、打包输出路径、静态资源路径、是否生成源映射等等。为了更好地理解vue.config.js配置,我会分步骤来介绍一些常用的配置选项。 首先,我们可以使用configureWebpack选项来修改Webpack的配置。比如,要在生产环境中修改配置,可以通过设置config.mode为'production'来指定模式。而config.performance则可以用来设置打包文件的大小限制。引用中的代码示例展示了如何进行这样的配置。 其次,我们还可以使用chainWebpack选项来链式操作Webpack的配置。在这里,你可以通过config.resolve.alias来设置路径别名,以方便你在项目中引用模块。比如,可以使用.set('@', resolve('src'))来将'@'设置为指向'src'目录的别名。 另外,如果你想对打包后的文件进行压缩,你可以使用CompressionWebpackPlugin插件。引用中的代码示例展示了如何在vue.config.js中引用该插件,并使用它进行压缩。 综上所述,vue.config.js提供了丰富的配置选项,可以让你对Vue项目进行灵活的配置和定制。你可以根据项目需求来设置不同的选项,以满足你的开发和生产需求。<span class="em">1</span><span class="em">2</span><span class="em">3</span><span class="em">4</span>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值