[英](Code Refactoring) shell command using child_process in javascript
我正在做一個 nuxt.js / vue.js 項目並應用原子設計方法,這意味着組件將被划分為每個文件夾中的數百個組件
/components
/atoms
/molecules
/organisms
我想要並且需要以分組和智能的方式導入,所以我這樣做:
在webpack.config.js
或nuxt.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
的內容,減少重復性?
歡迎任何代碼重構。
提前致謝。
它只是一個 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)
編輯解析 ls 是不安全的。 這是一個更好的方法:
for item in components/*;
do
# do something with item
done
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.