Reputation: 9454
In a current webpack project my code is partitioned into modules, each which has a main entry point with a .module.js
ending. E.g. for the module Util
, the entry point is util.module.js
and I include it in other modules by writing import util from 'modules/util/util.module.js'
However, since all modules have the same syntax for the entry point, I would rather avoid specifying the full filename of the entry. E.g, it would be nice if I could just write import util from 'modules/util'
.
I know this works if util.module.js
is name index.js
, but how can I tell Webpack to pick up my current module entries in the same way?
Upvotes: 3
Views: 1900
Reputation: 33660
I'll attempt to outline some readily available approaches, starting from your requirements and progressing towards something that's more conventional.
I sense that some overengineering of build tools might be creeping in, so I'd highly recommend you think again whether all of this is really necessary and reconsider the conventional approach.
It is analogous to how others would expect modules get to resolved, does not require Webpack and will not break other tools that internally attempt to resolve modules according to this strategy, like eslint-plugin-import.
Since you need to include the directory name in the module you're trying to resolve, you can use the NormalModuleReplacementPlugin
to construct the resolve path dynamically:
new webpack.NormalModuleReplacementPlugin(/modules\/(\w+)$/, (result) => {
result.request += `/${result.request.split('/').pop()}.module.js`
}
You'd need to play around with this to ensure all valid names are covered.
resolve.extensions
If you really want to somehow distinguish these modules, then you could do so by providing a specific extension for them:
modules/util/index.module.js
modules/dashboard/index.module.js
It would be enough to configure:
{
resolve: {
extensions: ['.js', '.module.js']
}
}
Another approach would be to extract all your modules as packages, specifying {main}
in package.json.
This will set you on a path towards a monorepository.
The conventional approach would be to name the modules index.js
:
modules/util/index.js
modules/dashboard/index.js
Upvotes: 6