vue代理的devServer中before设置mock后和真实接口对接的问题

使用mock后会在network中显示接口(两种情况)

第一种:在network中显示mock调接口的Name,此处不使用devServer代理

如图:

在这里插入图片描述
如果在network中显示,这时候不使用devServer代理的proxy,代码我贴出来如下:

'use strict'
const path = require('path')
// const SkeletonWebpackPlugin = require('vue-skeleton-webpack-plugin')
// const defaultSettings = require('./src/settings.js')

// 代码压缩
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')

// 压缩
const CompressionPlugin = require('compression-webpack-plugin')
const {
  log
} = require('console')
const productionGzipExtensions = /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i

// 报告查看
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin

function resolve(dir) {
  return path.join(__dirname, dir)
}

// const name = defaultSettings.title || '后台系统' // page title

// If your port is set to 80,
// use administrator privileges to execute the command line.
// For example, Mac: sudo npm run
// You can change the port by the following methods:
// port = 9528 npm run dev OR npm run dev --port = 9528
const port = process.env.port || process.env.npm_config_port || 9528 // dev port

// All configuration item explanations can be find in https://cli.vuejs.org/config/
module.exports = {
  /**
   * You will need to set publicPath if you plan to deploy your site under a sub path,
   * for example GitHub Pages. If you plan to deploy your site to https://foo.github.io/bar/,
   * then publicPath should be set to "/bar/".
   * In most cases please use '/' !!!
   * Detail: https://cli.vuejs.org/config/#publicpath
   */
  publicPath: process.env.ENV === 'production' ? '/' : '/',
  outputDir: 'dist',
  assetsDir: 'static',
  lintOnSave: process.env.NODE_ENV === 'development',
  productionSourceMap: false,
  devServer: {
    host: 'localhost', // target host
    port: port,
    overlay: {
      warnings: false,
      errors: true
    },
    // proxy: {
    //   // change xxx-api/login => mock/login
    //   // detail: https://cli.vuejs.org/config/#devserver-proxy
    //   [process.env.VUE_APP_BASE_API]: {
    //     target:'http://localhost:5002',
    //     changeOrigin: true,
    //     logLevel: 'debug',
    //     pathRewrite: {
    //       ['^' + process.env.VUE_APP_BASE_API]: ''
    //     },
    //     // 用于测试 代理时打印的数据如下:
    //     onProxyReq(proxyReq, req, res) {
    //       // console.log('proxyReq ---- http://localhost:5002', proxyReq, req, res)
    //     }
    //   }
    // },
    
    // you can run a mock server before this api ready
    // after or before 都可以
    before: require('./mock/mock-server.js')
  },
  configureWebpack: {
    // provide the app's title in webpack's name field, so that
    // it can be accessed in index.html to inject the correct title.
    // name: name,
    resolve: {
      alias: {
        '@': resolve('src')
      }
    },
    // 优化
    optimization: {
      minimizer: [
        new UglifyJsPlugin({
          uglifyOptions: {
            output: { // 删除注释
              comments: false
            },
            //生产环境自动删除console
            compress: {
              //warnings: false, // 若打包错误,则注释这行
              drop_debugger: true, //清除 debugger 语句
              drop_console: true, //清除console语句
              pure_funcs: ['console.log']
            }
          },
          sourceMap: false,
          parallel: true
        })
      ]
    },
  },
  // css: {
  //   extract: true // 是否使用css分离插件 ExtractTextPlugin(开启骨架屏必须这个配置)
  // },
  chainWebpack(config) {
    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/icons'))
      .end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/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')
        }
      )

    // config
    //   .plugin('webpack-bundle-analyzer')
    //   .use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin)


    // gzip
    if (process.env.NODE_ENV === 'production') {
      config.plugin('compressionPlugin')
        .use(new CompressionPlugin({
          filename: '[path].gz[query]',
          algorithm: 'gzip', // 使用gzip压缩
          test: productionGzipExtensions, // 匹配文件名
          threshold: 10240, // 对超过10k的数据压缩
          minRatio: 0.8, // 压缩率小于0.8才会压缩
          deleteOriginalAssets: true // 是否删除未压缩的源文件,谨慎设置,如果希望提供非gzip的资源,可不设置或者设置为false(比如删除打包后的gz后还可以加载到原始资源文件)
        }))
    }

    // 添加可视化工具 - 查看打包后的文件大小!
    if (process.env.NODE_ENV === 'production') {
      if (process.env.npm_config_report) {
        config
          .plugin('webpack-bundle-analyzer')
          .use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin)
          .end()
        config.plugins.delete('prefetch')
      }
    }

    // 骨架屏配置
    // config
    //   .plugin('SkeletonWebpackPlugin')
    //   .use(new SkeletonWebpackPlugin({
    //     webpackConfig: {
    //       entry: {
    //         app: resolve('src/skeleton.js'),
    //       }
    //     },
    //     minimize: true,
    //     quiet: true,
    //     router: {
    //       mode: 'history',
    //       routes: [{
    //         path: '*',
    //         skeletonId: 'common-skeleton'
    //       }]
    //     }
    //   }))
  },
  // css: {
  //   // 适配时使用
  //   loaderOptions: {
  //     css: {},
  //     postcss: {
  //       plugins: [
  //         require('postcss-px2rem')({
  //           remUnit: 192
  //         })
  //       ]
  //     }
  //   }
  // },
}

// module.exports = {
//   publicPath: './',
//   assetsDir: 'static',
//   productionSourceMap: false,
//   lintOnSave:false,
//   devServer: {
//     proxy: {
//       '/api':{
//         target:'http://www.fqniu.xyz:5000.com',
//         changeOrigin:true,
//         pathRewrite:{
//           '/api':''
//         }
//       }
//     }
//   }
// }

其中这里的after: require('./mock/mock-server.js'),是调用的mock封装的接口;

其中main.js中有段代码,后面会修改里面的配置,如下:

/**
 * If you don't want to use mock-server
 * you want to use MockJs for mock api
 * you can execute: mockXHR()
 *
 * Currently MockJs will be used in the production environment,
 * please remove it before going online ! ! !
 */
if (process.env.NODE_ENV === 'production') {
  const { mockXHR } = require('../mock')
  mockXHR()
}
第二种:在network中显示mock调接口的Name,此处使用devServer的代理
'use strict'
const path = require('path')
// const SkeletonWebpackPlugin = require('vue-skeleton-webpack-plugin')
// const defaultSettings = require('./src/settings.js')

// 代码压缩
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')

// 压缩
const CompressionPlugin = require('compression-webpack-plugin')
const {
  log
} = require('console')
const productionGzipExtensions = /\.(js|css|json|txt|html|ico|svg)(\?.*)?$/i

// 报告查看
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin

function resolve(dir) {
  return path.join(__dirname, dir)
}

// const name = defaultSettings.title || '后台系统' // page title

// If your port is set to 80,
// use administrator privileges to execute the command line.
// For example, Mac: sudo npm run
// You can change the port by the following methods:
// port = 9528 npm run dev OR npm run dev --port = 9528
const port = process.env.port || process.env.npm_config_port || 9528 // dev port

// All configuration item explanations can be find in https://cli.vuejs.org/config/
module.exports = {
  /**
   * You will need to set publicPath if you plan to deploy your site under a sub path,
   * for example GitHub Pages. If you plan to deploy your site to https://foo.github.io/bar/,
   * then publicPath should be set to "/bar/".
   * In most cases please use '/' !!!
   * Detail: https://cli.vuejs.org/config/#publicpath
   */
  publicPath: process.env.ENV === 'production' ? '/' : '/',
  outputDir: 'dist',
  assetsDir: 'static',
  lintOnSave: process.env.NODE_ENV === 'development',
  productionSourceMap: false,
  devServer: {
    host: 'localhost', // target host
    port: port,
    overlay: {
      warnings: false,
      errors: true
    },
    proxy: {
      // change xxx-api/login => mock/login
      // detail: https://cli.vuejs.org/config/#devserver-proxy
      [process.env.VUE_APP_BASE_API]: {
        target:'http://localhost:5002',
        changeOrigin: true,
        logLevel: 'debug',
        pathRewrite: {
          ['^' + process.env.VUE_APP_BASE_API]: ''
        },
        // 用于测试 代理时打印的数据如下:
        onProxyReq(proxyReq, req, res) {
          // console.log('proxyReq ---- http://localhost:5002', proxyReq, req, res)
        }
      }
    },
    // you can run a mock server before this api ready 
    // after or before 都可以
    before: require('./mock/mock-server.js')
  },
  configureWebpack: {
    // provide the app's title in webpack's name field, so that
    // it can be accessed in index.html to inject the correct title.
    // name: name,
    resolve: {
      alias: {
        '@': resolve('src')
      }
    },
    // 优化
    optimization: {
      minimizer: [
        new UglifyJsPlugin({
          uglifyOptions: {
            output: { // 删除注释
              comments: false
            },
            //生产环境自动删除console
            compress: {
              //warnings: false, // 若打包错误,则注释这行
              drop_debugger: true, //清除 debugger 语句
              drop_console: true, //清除console语句
              pure_funcs: ['console.log']
            }
          },
          sourceMap: false,
          parallel: true
        })
      ]
    },
  },
  // css: {
  //   extract: true // 是否使用css分离插件 ExtractTextPlugin(开启骨架屏必须这个配置)
  // },
  chainWebpack(config) {
    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/icons'))
      .end()
    config.module
      .rule('icons')
      .test(/\.svg$/)
      .include.add(resolve('src/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')
        }
      )

    // config
    //   .plugin('webpack-bundle-analyzer')
    //   .use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin)


    // gzip
    if (process.env.NODE_ENV === 'production') {
      config.plugin('compressionPlugin')
        .use(new CompressionPlugin({
          filename: '[path].gz[query]',
          algorithm: 'gzip', // 使用gzip压缩
          test: productionGzipExtensions, // 匹配文件名
          threshold: 10240, // 对超过10k的数据压缩
          minRatio: 0.8, // 压缩率小于0.8才会压缩
          deleteOriginalAssets: true // 是否删除未压缩的源文件,谨慎设置,如果希望提供非gzip的资源,可不设置或者设置为false(比如删除打包后的gz后还可以加载到原始资源文件)
        }))
    }

    // 添加可视化工具 - 查看打包后的文件大小!
    if (process.env.NODE_ENV === 'production') {
      if (process.env.npm_config_report) {
        config
          .plugin('webpack-bundle-analyzer')
          .use(require('webpack-bundle-analyzer').BundleAnalyzerPlugin)
          .end()
        config.plugins.delete('prefetch')
      }
    }

    // 骨架屏配置
    // config
    //   .plugin('SkeletonWebpackPlugin')
    //   .use(new SkeletonWebpackPlugin({
    //     webpackConfig: {
    //       entry: {
    //         app: resolve('src/skeleton.js'),
    //       }
    //     },
    //     minimize: true,
    //     quiet: true,
    //     router: {
    //       mode: 'history',
    //       routes: [{
    //         path: '*',
    //         skeletonId: 'common-skeleton'
    //       }]
    //     }
    //   }))
  },
  // css: {
  //   // 适配时使用
  //   loaderOptions: {
  //     css: {},
  //     postcss: {
  //       plugins: [
  //         require('postcss-px2rem')({
  //           remUnit: 192
  //         })
  //       ]
  //     }
  //   }
  // },
}

其中main.js中配置mock如下:

/**
 * If you don't want to use mock-server
 * you want to use MockJs for mock api
 * you can execute: mockXHR()
 *
 * Currently MockJs will be used in the production environment,
 * please remove it before going online ! ! !
 */
 if (process.env.NODE_ENV === 'production') {
  const { mockXHR } = require('../mock')
  mockXHR()
}

这时候发现mock和代理的接口都调通了,且在network中都显示出来了
在这里插入图片描述

第三种:在network中不显示mock调接口的Name,此处使用devServer代理

代理代码和第二种一样的情况,不同的是main.js中的环境如下:

其中main.js中配置mock如下:

/**
 * If you don't want to use mock-server
 * you want to use MockJs for mock api
 * you can execute: mockXHR()
 *
 * Currently MockJs will be used in the production environment,
 * please remove it before going online ! ! !
 */
 // 注意这里如果写开发环境 network是没有显示mock的接口Name
 if (process.env.NODE_ENV === 'production' || process.env.NODE_ENV === 'development') {
  const { mockXHR } = require('../mock')
  mockXHR()
}

注意这时候代理的如图一的接口是可以调用,mock的数据也可以调用,只是mock的数据在network中看不到了,如图二打印台是看到数据已经打印出来;

如图一:
在这里插入图片描述
如图二:
在这里插入图片描述

Logo

前往低代码交流专区

更多推荐