【问题标题】:(Code Refactoring) shell command using child_process in javascript(代码重构)在 javascript 中使用 child_process 的 shell 命令
【发布时间】:2023-03-18 20:07:01
【问题描述】:

我正在做一个 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 的内容不那么重复?

欢迎任何代码重构。

提前致谢。

【问题讨论】:

  • 这真的是个问题吗? “重构我的代码”似乎不是一个问题。目前尚不清楚成功答案的参数是什么。

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


【解决方案1】:

它只是一个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

如果你真的想偷偷摸摸,并且你知道组件目录中的每个子目录都需要迭代,那么你甚至可以将第一行替换为:

parameters=$(ls components)

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

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

【讨论】:

  • 如果你重构我的代码,这足以成为一个成功的响应,我非常感激。
  • 你认为你有办法为这个函数编写一个shell脚本,直接进入回调钩子吗?
  • @oguzismail,感谢您指出这一点。用更安全的东西更新我的答案。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-01-15
  • 2015-07-31
  • 1970-01-01
  • 2021-08-23
  • 1970-01-01
  • 2020-12-12
  • 1970-01-01
相关资源
最近更新 更多