欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

用 node 实现类似 webpack 的 require.context()功能

程序员文章站 2022-07-14 20:51:03
...

用 node 实现类似 webpack 的 require.context()功能

简介:最近在写 nuxt 的项目,因为是服务端渲染,需要加载大量国际化文件,一个一个导入太费劲,于是想自动导入,首先想到的是 webpack 的 require.context()功能,可是服务端渲染用不了。于是自己用 node 写了一个文件加载器。

文件目录

.
├── autoLoadFile.js
└── langs
    ├── app
    │   ├── en.js
    │   └── zh.js
    ├── en.js
    └── zh.js

langs/en.js

// langs/app/en.js内容和这一样,加了app前缀
const en = {
  lang: 'en'
}

module.exports = en

langs/zh.js

// langs/app/en.js内容和这一样,加了app前缀
const zh = {
  lang: '中文''
}

module.exports = zh

核心实现 autoLoadFile.js

#!/usr/bin/env node
const path = require('path')
const fs = require('fs')
const getPathInfo = p => path.parse(p)

/**
 * @description // 递归读取文件,类似于webpack的require.context()
 * @time 2020-9-12
 *
 * @param {String} directory 文件目录
 * @param {Boolean} useSubdirectories 是否查询子目录,默认false
 * @param {array} extList 查询文件后缀,默认 ['.js']
 *
 */
function autoLoadFile(directory, useSubdirectories = false, extList = ['.js']) {
  const filesList = []
  // 递归读取文件
  function readFileList(directory, useSubdirectories, extList) {
    const files = fs.readdirSync(directory)
    files.forEach(item => {
      const fullPath = path.join(directory, item)
      const stat = fs.statSync(fullPath)
      if (stat.isDirectory() && useSubdirectories) {
        readFileList(path.join(directory, item), useSubdirectories, extList)
      } else {
        const info = getPathInfo(fullPath)
        extList.includes(info.ext) && filesList.push(fullPath)
      }
    })
  }
  readFileList(directory, useSubdirectories, extList)
  // 生成需要的对象
  const res = filesList.map(item => ({
    path: item,
    data: require(item),
    ...getPathInfo(item)
  }))

  return res
}

const fileList = autoLoadFile(path.join(__dirname, './langs'))
console.log(fileList)

输出结果

autoLoadFile.js 所在目录下执行autoLoadFile.js

 node autoLoadFile.js

输出结果

[
  {
    path: '/Users/youqun/Saifu-Chemical-Admin/tests/langs/app/en.js',
    data: { lang: 'app-en' },
    root: '/',
    dir: '/Users/youqun/Saifu-Chemical-Admin/tests/langs/app',
    base: 'en.js',
    ext: '.js',
    name: 'en'
  },
  {
    path: '/Users/youqun/Saifu-Chemical-Admin/tests/langs/app/zh.js',
    data: { lang: 'app-中文' },
    root: '/',
    dir: '/Users/youqun/Saifu-Chemical-Admin/tests/langs/app',
    base: 'zh.js',
    ext: '.js',
    name: 'zh'
  },
  {
    path: '/Users/youqun/Saifu-Chemical-Admin/tests/langs/en.js',
    data: { lang: 'en' },
    root: '/',
    dir: '/Users/youqun/Saifu-Chemical-Admin/tests/langs',
    base: 'en.js',
    ext: '.js',
    name: 'en'
  },
  {
    path: '/Users/youqun/Saifu-Chemical-Admin/tests/langs/zh.js',
    data: { lang: '中文' },
    root: '/',
    dir: '/Users/youqun/Saifu-Chemical-Admin/tests/langs',
    base: 'zh.js',
    ext: '.js',
    name: 'zh'
  }
]