另外發(fā)有一篇mockjs的,比這篇簡單椿访。
vue/cli 5.0.0
相關(guān)依賴:compression-webpack-plugin webpack-bundle-analyzer unplugin-auto-import unplugin-vue-components mock json5
vue.config.js
const { defineConfig } = require("@vue/cli-service");
const CompressionPlugin = require('compression-webpack-plugin')
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin
const AutoImport = require('unplugin-auto-import/webpack')
const Components = require('unplugin-vue-components/webpack')
const { ElementPlusResolver } = require('unplugin-vue-components/resolvers')
const prodGzipExtensions = ['js', 'css', 'png', 'jpg']
module.exports = defineConfig({
transpileDependencies: true,
productionSourceMap: false,
lintOnSave: false,
devServer: {
// webpack5
setupMiddlewares: require('./mock/index')
// 其他版本的
// onBeforeSetupMiddleware: require('./mock/index')
// before: require('./mock/index')
},
configureWebpack: (config) => {
// 壓縮優(yōu)化
const plugins = []
plugins.push(
new CompressionPlugin({
algorithm: 'gzip',
test: new RegExp("\\.(" + prodGzipExtensions.join('|') + ")$"),
threshold: 1024 * 10,
minRatio: 0.8
}),
// new BundleAnalyzerPlugin(),
new webpack.optimize.LimitChunkCountPlugin({
maxChunks: 5
}),
new webpack.optimize.MinChunkSizePlugin({
minChunkSize: 5
}),
// 按需引入
AutoImport({
resolvers: [ElementPlusResolver()],
}),
Components({
resolvers: [ElementPlusResolver()],
})
)
config.plugins = [...config.plugins, ...plugins]
}
});
環(huán)境變量 .env.development
MOCK = true
mock 文件夾
const fs = require('fs')
const path = require('path')
const Mock = require('mockjs')
const JSONS = require('json5')
function getData(filePath) {
const json = fs.readFileSync(path.resolve(__dirname, filePath), 'utf-8')
return JSONS.parse(json)
}
// 這里也會根據(jù)webpack版本不同而有所改變
module.exports = function (middlewares, devServe) {
if (process.env.MOCK === 'true') {
middlewares.unshift({
path: "/user/userInfo",
middleware: (req, res) => {
console.log(111);
// mock 數(shù)據(jù)模擬接口數(shù)據(jù), 這里可以換成js文件漓拾,不需要再讀取json文件那么麻煩
// js文件就可以直接獲取對應(yīng)的變量名即可
let json = getData("./userInfo.json")
res.json(Mock.mock(json));
},
})
}
return middlewares;
}
// 不同版本的
module.exports = function (devServer) {
if (process.env.MOCK == "true") { 阁最、
devServer.app.post("/user/userInfo", function (rep, res) {、
var json = getJsonFile("./userInfo.json");
res.json(Mock.mock(json));
});
}
};
userInfo.json
{
"code": 200,
"data": {
"id": "1",
"name": "lisi"
}
}
接口使用
axios.get("/user/userInfo").then((res) => {
console.log(res);
});