vue-cli脚手架中配置webpack.dev.conf.js文件实现数据模拟

责编:menVScode 2018-02-07 0:45 阅读(1607)

1、根目录下创建要模拟数据的文件 db.json

{
  "getNewsList": [
    {
      "id": 1,
      "title": "新闻条目1新闻条目1新闻条目1新闻条目1",
      "url": "http://starcraft.com"
    }
  ],
  "login": {
    "username": "yudongdong",
    "userId": 123123
  },
  "getOrderList": {
    "list": [
      {
        "orderId": "ddj123",
        "product": "数据统计",
        "version": "高级版",
        "period": "1年",
        "buyNum": 2,
        "date": "2016-10-10",
        "amount": "500元"
      }
    ]
  }
}

2、目录 build/webpack.dev.conf.js 文件中添加:

var express = require('express')
var apiServer = express()
var bodyParser = require('body-parser')
apiServer.use(bodyParser.urlencoded({ extended: true }))
apiServer.use(bodyParser.json())
var apiRouter = express.Router()
var fs = require('fs')

在webpack.dev.conf.js 文件找到 devServer ,添加如下代码:

before(apiServer){
  apiRouter.route('/:apiName')
  .all(function (req, res) {
    fs.readFile('./db.json', 'utf8', function (err, data) {
      if (err) throw err
      var data = JSON.parse(data)
      if (data[req.params.apiName]) {
        res.json(data[req.params.apiName])  
      }else {
        res.send('no such api name')
      }
    })
  })
  apiServer.use('/api', apiRouter);

  apiServer.listen(3000, function (err) {
    if (err) {
      console.log(err)
      return
    }
    console.log('Listening at http://localhost:3000' + '\n')
  })
}

webpack.dev.conf.js 完整代码

'use strict'
const utils = require('./utils')
const webpack = require('webpack')
const config = require('../config')
const merge = require('webpack-merge')
const path = require('path')
const baseWebpackConfig = require('./webpack.base.conf')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const FriendlyErrorsPlugin = require('friendly-errors-webpack-plugin')
const portfinder = require('portfinder')

//数据模拟
var express = require('express')
var apiServer = express()
var bodyParser = require('body-parser')
apiServer.use(bodyParser.urlencoded({ extended: true }))
apiServer.use(bodyParser.json())
var apiRouter = express.Router()
var fs = require('fs')

const HOST = process.env.HOST
const PORT = process.env.PORT && Number(process.env.PORT)

const devWebpackConfig = merge(baseWebpackConfig, {
  module: {
    rules: utils.styleLoaders({ sourceMap: config.dev.cssSourceMap, usePostCSS: true })
  },
  // cheap-module-eval-source-map is faster for development
  devtool: config.dev.devtool,

  // these devServer options should be customized in /config/index.js
  devServer: {
    clientLogLevel: 'warning',
    historyApiFallback: {
      rewrites: [
        { from: /.*/, to: path.posix.join(config.dev.assetsPublicPath, 'index.html') },
      ],
    },
    hot: true,
    contentBase: false, // since we use CopyWebpackPlugin.
    compress: true,
    host: HOST || config.dev.host,
    port: PORT || config.dev.port,
    open: config.dev.autoOpenBrowser,
    overlay: config.dev.errorOverlay
      ? { warnings: false, errors: true }
      : false,
    publicPath: config.dev.assetsPublicPath,
    proxy: config.dev.proxyTable,
    quiet: true, // necessary for FriendlyErrorsPlugin
    watchOptions: {
      poll: config.dev.poll,
    },
    //数据模拟
    before(apiServer){
      apiRouter.route('/:apiName')
      .all(function (req, res) {
        fs.readFile('./db.json', 'utf8', function (err, data) {
          if (err) throw err
          var data = JSON.parse(data)
          if (data[req.params.apiName]) {
            res.json(data[req.params.apiName])  
          }else {
            res.send('no such api name')
          }
        })
      })
      apiServer.use('/api', apiRouter);

      apiServer.listen(3000, function (err) {
        if (err) {
          console.log(err)
          return
        }
        console.log('Listening at http://localhost:3000' + '\n')
      })
    }
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env': require('../config/dev.env')
    }),
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NamedModulesPlugin(), // HMR shows correct file names in console on update.
    new webpack.NoEmitOnErrorsPlugin(),
    // https://github.com/ampedandwired/html-webpack-plugin
    new HtmlWebpackPlugin({
      filename: 'index.html',
      template: 'index.html',
      inject: true
    }),
    // copy custom static assets
    new CopyWebpackPlugin([
      {
        from: path.resolve(__dirname, '../static'),
        to: config.dev.assetsSubDirectory,
        ignore: ['.*']
      }
    ])
  ]
})

module.exports = new Promise((resolve, reject) => {
  portfinder.basePort = process.env.PORT || config.dev.port
  portfinder.getPort((err, port) => {
    if (err) {
      reject(err)
    } else {
      // publish the new Port, necessary for e2e tests
      process.env.PORT = port
      // add port to devServer config
      devWebpackConfig.devServer.port = port

      // Add FriendlyErrorsPlugin
      devWebpackConfig.plugins.push(new FriendlyErrorsPlugin({
        compilationSuccessInfo: {
          messages: [`Your application is running here: http://${devWebpackConfig.devServer.host}:${port}`],
        },
        onErrors: config.dev.notifyOnErrors
        ? utils.createNotifierCallback()
        : undefined
      }))

      resolve(devWebpackConfig)
    }
  })
})

每改动webpack.dev.conf.js内容,最好重新启动一次:npm run dev。

3、在 config/index.js 文件中的dev对象里设置代理:

proxyTable: {
    '/api': {
        target: 'http://localhost:3000/', // 通过本地服务器将你的请求转发到这个地址
        changeOrigin: true, // 设置这个参数可以避免跨域
        pathRewrite: {
          '/api': '/'
        }
    }
}

这种方法支持post、get等方式,只要是用到 all()。

前端交流群: MVC前端网(menvscode.com)-qq交流群:551903636

邮箱快速注册

忘记密码