vue cli - 04 配置参数

2019-11-28  本文已影响0人  Lisa_Guo

VUE CLI 3封装了项目需要的大部分配置,但如果需要更改配置,可通过vue.config.js文件修改配置参数

// vue.config.js
module.exports = {
  // 各种配置项
}

pages

默认项目为单页面,可通过pages配置为多页面

注意事项:所有目录地址开头不能加斜杠'/'。不能写为'/src/index/main.js'

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'
  }
}

configureWebpack

对webpack配置进行定制

如果值为一个对象,该对象会被webpack-merge合并入最终的webpack配置
注意事项:publicPath,output.path需通过vue的配置,不可以在此处修改。

module.exports = {
    configureWebpack: {
      optimization: {
        minimize: false
      }
    }
}

如果值为一个函数,该函数接受config配置对象为参数,函数内修改配置后返回最终webpack配置

// vue.config.js
module.exports = {
  configureWebpack: config => {
    if (process.env.NODE_ENV === 'production') {
      // 为生产环境修改配置...
    } else {
      // 为开发环境修改配置...
    }
  }
}

chainWebpack

通过webpack-chain,可以通过API的方式操作webpack配置,使其可以方便的对loader和plugin进行定制操作

// vue.config.js
module.exports = {
  chainWebpack: config => {
    config.module
      .rule('vue')
      .use('vue-loader')
        .loader('vue-loader')
        .tap(options => {
          // 修改它的选项...
          return options
        })
  }
}

CSS 自动引入

如果你想自动化导入文件 (用于颜色、变量、mixin……),你可以使用 style-resources-loader。这里有一个关于 Stylus 的在每个单文件组件和 Stylus 文件中导入 ./src/styles/imports.styl 的例子:

// vue.config.js
const path = require('path')

module.exports = {
  chainWebpack: config => {
    const types = ['vue-modules', 'vue', 'normal-modules', 'normal']
    types.forEach(type => addStyleResource(config.module.rule('stylus').oneOf(type)))
  },
}

function addStyleResource (rule) {
  rule.use('style-resource')
    .loader('style-resources-loader')
    .options({
      patterns: [
        path.resolve(__dirname, './src/styles/imports.styl'),
      ],
    })
}

如果要改为其他类型,需修改config.module.rule('stylus').oneOf(type))rule()函数参数为项目使用的样式类型,如config.module.rule('scss').oneOf(type))

查看当前项目webpack配置

// 将配置输出在控制台
vue inspect
// 或输出到文件
vue inspect > output.js

// 查看inspect更多选项
vue inspect --help
上一篇下一篇

猜你喜欢

热点阅读