Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

生成环境打包mock好像用不了啊 #146

Open
zpliu1126 opened this issue Nov 3, 2024 · 0 comments
Open

生成环境打包mock好像用不了啊 #146

zpliu1126 opened this issue Nov 3, 2024 · 0 comments

Comments

@zpliu1126
Copy link

我在开发环境能正常使用,但是打包到生产环境后就出问题了

版本

"vite": "^5.4.10",
"vite-plugin-vue-devtools": "^7.3.1"
"mockjs": "^1.1.0",
"vite-plugin-mock": "^3.0.2",
 "vue": "^3.4.29",

vite.config.js 配置

// 文件路径 @/src/ vite.config.js
export default defineConfig({
  plugins: [
    vue(),
    vueDevTools(),
    viteMockServe({
      // default
      mockPath: 'mock',
      ignore: /^\_/,
      enable: true,
      logger: true,
      watchFiles: true
    })
  ],
  resolve: {
    alias: {
      '@': fileURLToPath(new URL('./src', import.meta.url))
    }
  }
})

mocker 接口配置

// 文件路径 @/mock/test.mock.ts
import { MockMethod } from 'vite-plugin-mock'

export default [
  {
    url: '/dist/api/carousl/info',
    method: 'get',
    response: () => {
      return {
        code: 0,
        data: {
          'list|1-10': [
            {
              title: '@title()',
              url: "@image('750x270', '#4A7BF7', 'Hello')"
            }
          ]
        }
      }
    }
  }
] as MockMethod[]

mockProdServer.ts配置

// 文件路径 @/src/mockProdServer.ts
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
import { createProdMockServer } from 'vite-plugin-mock/client'

const modules: {
  [key: string]: { default: object[] }
} = import.meta.glob('../mock/*.mock.ts', {
  eager: true
})

const mockModules: object[] = []
Object.keys(modules).forEach((key) => {
  if (key.includes('/_')) {
    return
  }
  mockModules.push(...modules[key].default)
})

/**
 * Used in a production environment. Need to manually import all modules
 */
export function setupProdMockServer() {
  createProdMockServer(mockModules)
  console.log(mockModules)
}

main.js 中引用

// 文件路径 @/src/main.js
if (process.env.NODE_ENV === 'production') {
  import('@/mockProdServer').then(({ setupProdMockServer }) => {
    setupProdMockServer()
  })
}

打包后在生产环境无法正常mock
image

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant