vue-element-admin mock目录下多个mock modules的js文件,能否通过类似webpack的require.context的方式引入,而不是手动import xxx from './xxx'

s3fp2yjn  于 4个月前  发布在  Webpack
关注(0)|答案(1)|浏览(153)

Question(提问)

Steps to reproduce(问题复现步骤)
Screenshot or Gif(截图或动态图)
Other relevant information(格外信息)
  • Your OS:
  • Node.js version:
  • vue-element-admin version:
6uxekuva

6uxekuva1#

自问自答一下吧
把各个 mock module 的 js 文件统一放在 mock/modules 目录下,然后在 mock/index.js 文件:

/**
* note: polyfill for require.context
* refer to https://stackoverflow.com/questions/38332094/how-can-i-mock-webpacks-require-context-in-jest/42191018#42191018
*/
// This condition actually should detect if it's an Node environment
if (typeof require.context === 'undefined') {
  const fs = require('fs')
  const path = require('path')

  require.context = (base = '.', scanSubDirectories = false, regularExpression = /\.[jt]s$/) => {
    const files = {}

    function readDirectory (directory) {
      fs.readdirSync(directory).forEach((file) => {
        const fullPath = path.resolve(directory, file)

        if (fs.statSync(fullPath).isDirectory()) {
          if (scanSubDirectories) readDirectory(fullPath)

          return
        }

        if (!regularExpression.test(fullPath)) return

        files[fullPath] = true
      })
    }

    readDirectory(path.resolve(__dirname, base))

    function Module (file) {
      // return require(path.resolve(__dirname, base, file))
      return require(file)
    }

    Module.keys = () => Object.keys(files)

    return Module
  }
}

const moduleFiles = require.context('./modules', true, /\.js$/)

// you do not need `import xxx from './modules/xxx'`
// it will auto require all mock modules from module files
/* Mock Modules */
const modules = moduleFiles.keys().reduce((modules, modulePath) => [...modules, moduleFiles(modulePath).default], [])

const mocks = [
  ...modules
]

......

相关问题