亲宝软件园·资讯

展开

vue.config.js configureWebpack与chainWebpack区别

zcm花开不败 人气:0

configureWebpack与chainWebpack区别

configureWebpack与chainWebpack的作用相同,唯一的区别就是他们修改webpack配置方式不同:

https://cli.vuejs.org/zh/config/#configurewebpack

configureWebpack 通过操作对象得形式来修改迷人得webpack配置,该对象将会呗webpack-merge合并入最终得webpack配置

chainWebpack 通过链式编程的形式来修改默认的webpack配置

1.configureWebpack

1.1configureWebpack对象形式  

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

1.2configureWebpack函数形式

const path = require('path');
function resolve(dir) {
  return path.join(__dirname,dir)
}
module.exports = {
 devServer: {
   ...
 },
 lintOnSave:false, // eslint-loader 是否在保存时候检查代码
 productionSourceMap: false, // 生产环境是否生成sourceMap 文件
 filenameHashing: true, // 文件hash
  configureWebpack: config => {
    if(process.env.NODE_ENV === 'production') {
      ...
    }else {
      ...
    }
    // 直接修改配置
    config.resolve.alias['assets'] = resolve('src/assets')
  }
}

或者

configureWebpack: config => {
  if(process.env.NODE_ENV){
    ...
  }else{
    ...
  }
  // 返回一个将要合并得对象
  return {
    resolve: {
      alias: {
        '@asset': resolve("src/assets")
      }
    }
  }
}

2.chainWebpack

修改Loader选项

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

添加一个新的Loader

module.exports = {
  chainWebpack: config => {
    config.module
    .rule('graphql')
    .test('/\.graphql$/')
    .use(''graphql-tag/loader')
     .loader('graphql-tag/loader)
     .end()
    // 你还可以再添加一个loader
    .use('other-loader')
      .loader('other-loader')
      .end()
  }
}

替换一个规则里的Loader

module.exports = {
  chainWebpack: config => {
    const svgRule = config.module.rule('svg')
    // 清楚已有的所有loader。
    // 如果你不这样做,接下来的loader会附加在该规则现有的 loader 之后。
    svgRule.uses.clear()
    // 添加要替换的 loader 
    svgRule
      .use('vue-svg-loader')
        .loader('vue-svg-loader')
  }
}

vue-cli中chainWebpack和configureWebpack

我们目前做的是国外的项目,考虑到东南亚浏览器版本低,所以公司采用了vue-cli2来搭建项目。

vue.config.js

当我们不知道config中有哪些属性或者方法的时候我们就可以采取函数的方式打印config然后再尝试这如何配置

函数 打印config

打印 configureWebpack中的config

const path = require('path')
const resolve = (dir) => path.join(__dirname, dir)
module.exports = {
  publicPath: './',
  runtimeCompiler: true,
  configureWebpack: (config) => {
    console.log(config)
  },
}

config结果为

  mode: 'production',
  context: 'C:\\Users\\shiyang.xue\\Desktop\\sems-pc',
  devtool: false,
  node: {
    setImmediate: false,
    process: 'mock',
    dgram: 'empty',
    fs: 'empty',
    net: 'empty',
    tls: 'empty',
    child_process: 'empty'
  },
  output: {
    path: 'C:\\Users\\shiyang.xue\\Desktop\\sems-pc\\dist',
    filename: 'js/[name].[contenthash:8].js',
    publicPath: '',
    chunkFilename: 'js/[name].[contenthash:8].js'
  },
  resolve: {
    alias: {
      '@': 'C:\\Users\\shiyang.xue\\Desktop\\sems-pc\\src', //别名
      'vue$': 'vue/dist/vue.esm.js'
    },
    extensions: [ '.mjs', '.js', '.jsx', '.vue', '.json', '.wasm' ],// vue解析时候查找文件的顺序
    modules: [ // modules包的文件位置
      'node_modules',
      'C:\\Users\\shiyang.xue\\Desktop\\sems-pc\\node_modules',
      'C:\\Users\\shiyang.xue\\Desktop\\sems-pc\\node_modules\\@vue\\cli-service\\node_modules'
    ],
    plugins: [ [Object] ]
  },
  resolveLoader: {
    modules: [
    // 这块就是modules的文件所在位置
    ],
    plugins: [ [Object] ]
  },
  module: {
    noParse: /^(vue|vue-router|vuex|vuex-router-sync)$/,
    rules: [
      [Object], [Object],
      [Object], [Object],
      [Object], [Object],
      [Object], [Object],
      [Object], [Object],
      [Object], [Object],
      [Object]
    ]
  },
  optimization: {
    splitChunks: { cacheGroups: [Object] },
    minimizer: [ [TerserPlugin] ]
  },
  plugins: [
    VueLoaderPlugin {},
    DefinePlugin { definitions: [Object] },
    CaseSensitivePathsPlugin {
      options: {},
      logger: [Object [console]],
      pathCache: Map(0) {},
      fsOperations: 0,
      primed: false
    },
    FriendlyErrorsWebpackPlugin {
      compilationSuccessInfo: {},
      onErrors: undefined,
      shouldClearConsole: true,
      formatters: [Array],
      transformers: [Array],
      previousEndTimes: {}
    },
    MiniCssExtractPlugin { options: [Object] },
    OptimizeCssnanoPlugin { options: [Object] },
    HashedModuleIdsPlugin { options: [Object] },
    NamedChunksPlugin { nameResolver: [Function (anonymous)] },
    HtmlWebpackPlugin { options: [Object] },
    PreloadPlugin { options: [Object] },
    PreloadPlugin { options: [Object] },
    CopyPlugin { patterns: [Array], options: {} }
  ],
  entry: { app: [ './src/main.js' ] }
}

有了以上的信息,你就知道如何配置了,config信息中没有发现performance这个属性但是你利用对象的处理方式就可以。

  configureWebpack: {
    performance: {
      hints: 'error', // 枚举
      maxAssetSize: 30000000, // 整数类型(以字节为单位) // 单个文件大小超出就提示
      maxEntrypointSize: 500000000, // 整数类型(以字节为单位) // 入口文件大小超出设定的值 就提示
      assetFilter: function (assetFilename) {
        // 提供资源文件名的断言函数
        return assetFilename.endsWith('.css') || assetFilename.endsWith('.js')
      }
    },
  },

这个和 vue-cli解析webpack的方式有关系,对象的方式解析的时候直接就取webpack原始的配置项目,然后再进行更新,而函数的方式只暴露一些常用的必须的方法或者属性,个人理解。

chainWebpack 函数式

const path = require('path')
const resolve = (dir) => path.join(__dirname, dir)
module.exports = {
  publicPath: './',
  runtimeCompiler: true,
  chainWebpack : (config) => {
    console.log(config)
  },
}

config打印

  
  parent: undefined,
  store: Map(3) {
    'mode' => 'production',
    'context' => 'C:\\Users\\shiyang.xue\\Desktop\\sems-pc',
    'devtool' => false
  },
  devServer: <ref *2> {
    parent: [Circular *1],
    store: Map(0) {},
    allowedHosts: { parent: [Circular *2], store: Set(0) {} },
    shorthands: [
      'after',            'before',             'bonjour',
      'clientLogLevel',   'color',              'compress',
      'contentBase',      'disableHostCheck',   'filename',
      'headers',          'historyApiFallback', 'host',
      'hot',              'hotOnly',            'http2',
      'https',            'index',              'info',
      'inline',           'lazy',               'mimeTypes',
      'noInfo',           'open',               'openPage',
      'overlay',          'pfx',                'pfxPassphrase',
      'port',             'proxy',              'progress',
      'public',           'publicPath',         'quiet',
      'setup',            'socket',             'sockHost',
      'sockPath',         'sockPort',           'staticOptions',
      'stats',            'stdin',              'useLocalIp',
      'watchContentBase', 'watchOptions',       'writeToDisk'
    ],
    after: [Function (anonymous)],
    before: [Function (anonymous)],
    bonjour: [Function (anonymous)],
    clientLogLevel: [Function (anonymous)],
    color: [Function (anonymous)],
    compress: [Function (anonymous)],
    contentBase: [Function (anonymous)],
    disableHostCheck: [Function (anonymous)],
    filename: [Function (anonymous)],
    headers: [Function (anonymous)],
    historyApiFallback: [Function (anonymous)],
    host: [Function (anonymous)],
    hot: [Function (anonymous)],
    hotOnly: [Function (anonymous)],
    http2: [Function (anonymous)],
    https: [Function (anonymous)],
    index: [Function (anonymous)],
    info: [Function (anonymous)],
    inline: [Function (anonymous)],
    lazy: [Function (anonymous)],
    mimeTypes: [Function (anonymous)],
    noInfo: [Function (anonymous)],
    open: [Function (anonymous)],
    openPage: [Function (anonymous)],
    overlay: [Function (anonymous)],
    pfx: [Function (anonymous)],
    pfxPassphrase: [Function (anonymous)],
    port: [Function (anonymous)],
    proxy: [Function (anonymous)],
    progress: [Function (anonymous)],
    public: [Function (anonymous)],
    publicPath: [Function (anonymous)],
    quiet: [Function (anonymous)],
    setup: [Function (anonymous)],
    socket: [Function (anonymous)],
    sockHost: [Function (anonymous)],
    sockPath: [Function (anonymous)],
    sockPort: [Function (anonymous)],
    staticOptions: [Function (anonymous)],
    stats: [Function (anonymous)],
    stdin: [Function (anonymous)],
    useLocalIp: [Function (anonymous)],
    watchContentBase: [Function (anonymous)],
    watchOptions: [Function (anonymous)],
    writeToDisk: [Function (anonymous)]
  },
  entryPoints: { parent: [Circular *1], store: Map(1) { 'app' => [Object] } },
  module: <ref *3> {
    parent: [Circular *1],
    store: Map(1) { 'noParse' => /^(vue|vue-router|vuex|vuex-router-sync)$/ },
    rules: { parent: [Circular *3], store: [Map] },
    defaultRules: { parent: [Circular *3], store: Map(0) {} },
    shorthands: [ 'noParse', 'strictExportPresence' ],
    noParse: [Function (anonymous)],
    strictExportPresence: [Function (anonymous)]
  },
  node: {
    parent: [Circular *1],
    store: Map(7) {
      'setImmediate' => false,
      'process' => 'mock',
      'dgram' => 'empty',
      'fs' => 'empty',
      'net' => 'empty',
      'tls' => 'empty',
      'child_process' => 'empty'
    }
  },
  optimization: <ref *4> {
    parent: [Circular *1],
    store: Map(1) { 'splitChunks' => [Object] },
    minimizers: { parent: [Circular *4], store: [Map] },
    shorthands: [
      'concatenateModules',
      'flagIncludedChunks',
      'mergeDuplicateChunks',
      'minimize',
      'namedChunks',
      'namedModules',
      'nodeEnv',
      'noEmitOnErrors',
      'occurrenceOrder',
      'portableRecords',
      'providedExports',
      'removeAvailableModules',
      'removeEmptyChunks',
      'runtimeChunk',
      'sideEffects',
      'splitChunks',
      'usedExports'
    ],
    concatenateModules: [Function (anonymous)],
    flagIncludedChunks: [Function (anonymous)],
    mergeDuplicateChunks: [Function (anonymous)],
    minimize: [Function (anonymous)],
    namedChunks: [Function (anonymous)],
    namedModules: [Function (anonymous)],
    nodeEnv: [Function (anonymous)],
    noEmitOnErrors: [Function (anonymous)],
    occurrenceOrder: [Function (anonymous)],
    portableRecords: [Function (anonymous)],
    providedExports: [Function (anonymous)],
    removeAvailableModules: [Function (anonymous)],
    removeEmptyChunks: [Function (anonymous)],
    runtimeChunk: [Function (anonymous)],
    sideEffects: [Function (anonymous)],
    splitChunks: [Function (anonymous)],
    usedExports: [Function (anonymous)]
  },
  output: {
    parent: [Circular *1],
    store: Map(4) {
      'path' => 'C:\\Users\\shiyang.xue\\Desktop\\sems-pc\\dist',
      'filename' => 'js/[name].[contenthash:8].js',
      'publicPath' => '',
      'chunkFilename' => 'js/[name].[contenthash:8].js'
    },
    shorthands: [
      'auxiliaryComment',
      'chunkCallbackName',
      'chunkFilename',
      'chunkLoadTimeout',
      'crossOriginLoading',
      'devtoolFallbackModuleFilenameTemplate',
      'devtoolLineToLine',
      'devtoolModuleFilenameTemplate',
      'devtoolNamespace',
      'filename',
      'futureEmitAssets',
      'globalObject',
      'hashDigest',
      'hashDigestLength',
      'hashFunction',
      'hashSalt',
      'hotUpdateChunkFilename',
      'hotUpdateFunction',
      'hotUpdateMainFilename',
      'jsonpFunction',
      'library',
      'libraryExport',
      'libraryTarget',
      'path',
      'pathinfo',
      'publicPath',
      'sourceMapFilename',
      'sourcePrefix',
      'strictModuleExceptionHandling',
      'umdNamedDefine',
      'webassemblyModuleFilename'
    ],
    auxiliaryComment: [Function (anonymous)],
    chunkCallbackName: [Function (anonymous)],
    chunkFilename: [Function (anonymous)],
    chunkLoadTimeout: [Function (anonymous)],
    crossOriginLoading: [Function (anonymous)],
    devtoolFallbackModuleFilenameTemplate: [Function (anonymous)],
    devtoolLineToLine: [Function (anonymous)],
    devtoolModuleFilenameTemplate: [Function (anonymous)],
    devtoolNamespace: [Function (anonymous)],
    filename: [Function (anonymous)],
    futureEmitAssets: [Function (anonymous)],
    globalObject: [Function (anonymous)],
    hashDigest: [Function (anonymous)],
    hashDigestLength: [Function (anonymous)],
    hashFunction: [Function (anonymous)],
    hashSalt: [Function (anonymous)],
    hotUpdateChunkFilename: [Function (anonymous)],
    hotUpdateFunction: [Function (anonymous)],
    hotUpdateMainFilename: [Function (anonymous)],
    jsonpFunction: [Function (anonymous)],
    library: [Function (anonymous)],
    libraryExport: [Function (anonymous)],
    libraryTarget: [Function (anonymous)],
    path: [Function (anonymous)],
    pathinfo: [Function (anonymous)],
    publicPath: [Function (anonymous)],
    sourceMapFilename: [Function (anonymous)],
    sourcePrefix: [Function (anonymous)],
    strictModuleExceptionHandling: [Function (anonymous)],
    umdNamedDefine: [Function (anonymous)],
    webassemblyModuleFilename: [Function (anonymous)]
  },
  performance: {
    parent: [Circular *1],
    store: Map(0) {},
    shorthands: [ 'assetFilter', 'hints', 'maxAssetSize', 'maxEntrypointSize' ],
    assetFilter: [Function (anonymous)],
    hints: [Function (anonymous)],
    maxAssetSize: [Function (anonymous)],
    maxEntrypointSize: [Function (anonymous)]
  },
  plugins: {
    parent: [Circular *1],
    store: Map(12) {
      'vue-loader' => [Object],
      'define' => [Object],
      'case-sensitive-paths' => [Object],
      'friendly-errors' => [Object],
      'extract-css' => [Object],
      'optimize-css' => [Object],
      'hash-module-ids' => [Object],
      'named-chunks' => [Object],
      'html' => [Object],
      'preload' => [Object],
      'prefetch' => [Object],
      'copy' => [Object]
    }
  },
  resolve: <ref *5> {
    parent: [Circular *1],
    store: Map(0) {},
    alias: { parent: [Circular *5], store: [Map] },
    aliasFields: { parent: [Circular *5], store: Set(0) {} },
    descriptionFiles: { parent: [Circular *5], store: Set(0) {} },
    extensions: { parent: [Circular *5], store: [Set] },
    mainFields: { parent: [Circular *5], store: Set(0) {} },
    mainFiles: { parent: [Circular *5], store: Set(0) {} },
    modules: { parent: [Circular *5], store: [Set] },
    plugins: { parent: [Circular *5], store: [Map] },
    shorthands: [
      'cachePredicate',
      'cacheWithContext',
      'concord',
      'enforceExtension',
      'enforceModuleExtension',
      'symlinks',
      'unsafeCache'
    ],
    cachePredicate: [Function (anonymous)],
    cacheWithContext: [Function (anonymous)],
    concord: [Function (anonymous)],
    enforceExtension: [Function (anonymous)],
    enforceModuleExtension: [Function (anonymous)],
    symlinks: [Function (anonymous)],
    unsafeCache: [Function (anonymous)]
  },
  resolveLoader: <ref *6> {
    parent: [Circular *1],
    store: Map(0) {},
    alias: { parent: [Circular *6], store: Map(0) {} },
    aliasFields: { parent: [Circular *6], store: Set(0) {} },
    descriptionFiles: { parent: [Circular *6], store: Set(0) {} },
    extensions: { parent: [Circular *6], store: Set(0) {} },
    mainFields: { parent: [Circular *6], store: Set(0) {} },
    mainFiles: { parent: [Circular *6], store: Set(0) {} },
    modules: { parent: [Circular *6], store: [Set] },
    plugins: { parent: [Circular *6], store: [Map] },
    shorthands: [
      'cachePredicate',
      'cacheWithContext',
      'concord',
      'enforceExtension',
      'enforceModuleExtension',
      'symlinks',
      'unsafeCache'
    ],
    cachePredicate: [Function (anonymous)],
    cacheWithContext: [Function (anonymous)],
    concord: [Function (anonymous)],
    enforceExtension: [Function (anonymous)],
    enforceModuleExtension: [Function (anonymous)],
    symlinks: [Function (anonymous)],
    unsafeCache: [Function (anonymous)],
    moduleExtensions: { parent: [Circular *6], store: Set(0) {} },
    packageMains: { parent: [Circular *6], store: Set(0) {} }
  },
  shorthands: [
    'amd',         'bail',
    'cache',       'context',
    'devtool',     'externals',
    'loader',      'mode',
    'name',        'parallelism',
    'profile',     'recordsInputPath',
    'recordsPath', 'recordsOutputPath',
    'stats',       'target',
    'watch',       'watchOptions'
  ],
  amd: [Function (anonymous)],
  bail: [Function (anonymous)],
  cache: [Function (anonymous)],
  context: [Function (anonymous)],
  devtool: [Function (anonymous)],
  externals: [Function (anonymous)],
  loader: [Function (anonymous)],
  mode: [Function (anonymous)],
  name: [Function (anonymous)],
  parallelism: [Function (anonymous)],
  profile: [Function (anonymous)],
  recordsInputPath: [Function (anonymous)],
  recordsPath: [Function (anonymous)],
  recordsOutputPath: [Function (anonymous)],
  stats: [Function (anonymous)],
  target: [Function (anonymous)],
  watch: [Function (anonymous)],
  watchOptions: [Function (anonymous)]
} 

chainWebpack中的config信息比较完成,而且详细,个人喜欢打印这个然后找具体的使用方法

对象的方式来配置,需要参照webapck文档来配置

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

加载全部内容

相关教程
猜你喜欢
用户评论