Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
139 views
in Technique[技术] by (71.8m points)

vue中如何使用reuiqre引入npm包

在vue中使用mock
在vue.config.js中

module.exports = {
  devServer: {
    before: require('./mock/index.js')
  }
};

./mock/index.js文件中

const fs = require('fs');
const path = require('path');
const Mock = require('mockjs');
const JSON5 = require('json5');

// 打印有效 并且确实存在mock和setup方法
console.log(Mock)
// 正确调用mock方法
console.log(Mock.mock({a:1}));
// 这里报错: Cannot read property 'setup' of undefined
Mock.setup({
  timeout: 2000
})
// 以上为关键代码



function getSql() {
  //读取文件
  let json5 = fs.readFileSync(path.join(__dirname, './sql.json5'), 'utf-8');
  //解析并返回
  return JSON5.parse(json5);
}


module.exports = function (app) {
  // 通过环境变量控制MOCK执行
  if (process.env.MOCK == 'true') {
    app.get('/mxkj/get_detail', function (rep, res) {
      res.json(Mock.mock(getSql()))
    });
  }
}

控制台
image.png


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

mockjs 代码中初始化XHR,因为在服务环境下没有window对象,所有XHR为undefined所有会报错
image.png


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...