将模块导出到对象,shell脚本

时间:2019-05-23 16:10:35

标签: javascript shell vue.js

我正在处理一个Nuxt.js项目,components文件夹看起来像这样:

/components/atoms/....files.vue
/components/molecules/....files.vue
/components/organisms/....files.vue
/components/templates/....files.vue

我需要将组件导出到单独的对象中,例如

atoms = {all components of the atom folder}
molecules = {all components of the paste of atoms}
organisms = {all components of the atom folder}
templates = {all components of the atom folder}

我有一个外壳,可在每个文件夹内生成一个index.js,它遵循代码

parameters=$(ls components)
for item in ${parameters[*]}
do
    ls components/$item/ | grep -v index.js | sed 's#^\([^.]*\).*$#export {default as \1} from "./&"#' > components/$item/index.js
done

结果,例如

/components/atoms/index.js

export { default as ButtonStyled } from './ButtonStyled.vue'
export { default as TextLead } from './TextLead.vue'
export { default as InputSearch } from './InputSearch.vue'
....

但这确实会分别导出每个组件,我需要的是导出对象内部的所有组件,如前所述,该对象带有文件夹名称。

我需要的输出

export atoms
export molecules
export organisms
export templates

我用javascript获得了所需的结果,但这是一个非常大且重复的代码。

const atoms = {}
const reqAtoms = require.context('@/components/atoms', true, /\.vue$/)
reqAtoms.keys().forEach(fileName => {
  const componentName = fileName.replace(/^.+\/([^/]+)\.vue/, '$1')
  atoms[componentName] = reqAtoms(fileName).default
})

const molecules = {}
const reqMolecules = require.context('@/components/molecules', true, /\.vue$/)
reqMolecules.keys().forEach(fileName => {
  const componentName = fileName.replace(/^.+\/([^/]+)\.vue/, '$1')
  molecules[componentName] = reqMolecules(fileName).default
})

const organisms = {}
const reqOrgarnisms = require.context('@/components/organisms', true, /\.vue$/)
reqOrgarnisms.keys().forEach(fileName => {
  const componentName = fileName.replace(/^.+\/([^/]+)\.vue/, '$1')
  organisms[componentName] = reqOrgarnisms(fileName).default
})

const templates = {}
const reqTemplates = require.context('@/components/templates', true, /\.vue$/)
reqTemplates.keys().forEach(fileName => {
  const componentName = fileName.replace(/^.+\/([^/]+)\.vue/, '$1')
  templates[componentName] = reqTemplates(fileName).default
})

export default {
  atoms,
  molecules,
  organisms,
  templates
}

有什么想法可以做得更小或使用shell脚本吗?

感谢您使用Shell Script甚至JavaScript的任何解决方案。

1 个答案:

答案 0 :(得分:0)

我将使用here-doc作为模板,而不是使用sed

allcomponents=()
for component in components/*
do
    component=${component##*/} # remove directory prefix
    allcomponents+=("$component")
    cat <<EOS
const $component = {}
const req$component = require.context('@/components/$component', true, /\.vue\$/)
req$component.keys().forEach(fileName => {
  const componentName = fileName.replace(/^.+\/([^/]+)\.vue/, '\$1')
  atoms[componentName] = req$component(fileName).default
})

EOS
done > exports.js
echo "export default {" >> exports.js
printf "  %s,\n" "${allcomponents[@]}" >> exports.js
echo "}" >> exports.js