[英]Automate imports from same directory
I have this file, which imports and mounts routes from components/*
directory.我有这个文件,它从components/*
目录导入和安装路由。
Is there any way I could automate this?有什么办法可以使它自动化吗?
// Middlewares
const authorizeMiddleware = require('../middlewares/authorize');
const authMiddleware = require('../middlewares/auth');
// load components
const aclComponent = require('../components/acl/acl.component');
const jobComponent = require('../components/job/job.component');
const zoneComponent = require('../components/zone/zone.component');
const authComponent = require('../components/auth/auth.component');
const cityComponent = require('../components/city/city.component');
const usersComponent = require('../components/user/user.component');
..
...
.....
function loadRoutes(router) {
router.use(
'/auth',
authComponent.AuthRoutes,
);
router.use(
'/users',
usersComponent.UsersRoutes,
);
..
...
....
return router;
}
module.exports = loadRoutes;
I have seen such things in typeorm
where it search for entities based on patterns.我在typeorm
中看到过这样的东西,它根据模式搜索实体。
Something similar to this,与此类似的东西,
{
"entities": ["dist/entity/**/*.js"],
"migrations": ["dist/migration/**/*.js"],
"subscribers": ["dist/subscriber/**/*.js"],
"cli": {
"entitiesDir": "src/entity",
"migrationsDir": "src/migration",
"subscribersDir": "src/subscriber"
}
I tried glob.js
and it did the work,我尝试glob.js
,它成功了,
const glob = require('glob');
const path = require('path');
// Use the glob package to match all files ending in ".component.js" in the "components" directory
const componentFiles = glob.sync(path.join(__dirname, 'components', '**', '*.component.js'));
function loadRoutes(router) {
// Iterate over the matched files and require each one
componentFiles.forEach((componentFile) => {
const component = require(componentFile);
// Extract the component name from the file name (e.g. "acl.component.js" => "acl")
const componentName = path.basename(componentFile, '.component.js');
// Mount the routes for the component on the router using the component name as the base path
router.use(`/${componentName}`, component.Routes);
});
return router;
}
module.exports = loadRoutes;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.