(代码重构)在javascript

时间:2019-05-03 22:39:52

标签: javascript node.js vue.js webpack sh

我正在研究nuxt.js / vue.js项目并应用原子设计方法,这意味着将每个文件夹中的组件分为数百个组件

/components
   /atoms
   /molecules
   /organisms

我想要并且需要以分组且智能的方式导入,所以我这样做:

webpack.config.jsnuxt.config.js

使用webpack中的Compiler Hooks进行每次构建,生成index.js导出组件

const exec = require('child_process').exec;

module.exports = {

  // ... other config here ...

  plugins: [

    // ... other plugins here ...

    {
        apply: compiler => {
          compiler.hooks.beforeCompile.tap('MyPlugin', compilation => {
            exec('sh assets/DynamicExport.sh', (err, stdout, stderr) => {
              if (stdout) process.stdout.write(stdout)
              if (stderr) process.stderr.write(stderr)
            })
          })
        }
      }
  ]
};

assets/DynamicExport.sh

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

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

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

然后通过导出文件夹的所有组件在每个文件夹中生成一个index.js文件

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

最后,我可以采用清晰,分组和智能的方式进行导入, 在我应用程序中的任何地方。

import {
    ButtonStyled,
    TextLead,
    InputSearch
} from '@/components/atoms'

import {
    SearchForm
} from '@/components/molecules'

一切正常,但是我发现解决方案有点大,在assets中调用一个文件,也许它还有另一种我不知道的方法..

是否有任何方法可以重构和降低assets/DynamicExport.sh的重复程度较低的内容?

任何代码重构都将受到欢迎。

谢谢。

1 个答案:

答案 0 :(得分:3)

这只是一个shell文件,因此您可以执行以下操作:

parameters=( atoms molecules organisms )
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目录中的每个子目录都需要迭代,那么您甚至可以将第一行替换为:

parameters=$(ls components)

EDIT 解析ls是不安全的。这是一种更好的方法:

for item in components/*; 
do
  # do something with item
done