我正在研究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
的重复程度较低的内容?
任何代码重构都将受到欢迎。
谢谢。
答案 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