【发布时间】:2023-03-18 20:07:01
【问题描述】:
我正在做一个 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 的内容不那么重复?
欢迎任何代码重构。
提前致谢。
【问题讨论】:
-
这真的是个问题吗? “重构我的代码”似乎不是一个问题。目前尚不清楚成功答案的参数是什么。
标签: javascript node.js vue.js webpack sh