javascript - Relative vs. non-relative module import for custom modules -
update[09/12/2017 16:58 est]
added reason why hesitate use natively-supported non-relative import own modules bottom of question.
update[09/12/2017 12:58 est]:
per request, made file structure below reflect actual use case. nested view module requesting utility module somewhere directory tree.
per request
in both typescript , es6, 1 can import custom module by
// relative import { numberutil } './number_util'; // or // non-relative import { numberutil } 'number_util';
and according typescript docs (link), 1 should:
... use relative imports own modules guaranteed maintain relative location @ runtime.
... use non-relative paths when importing of external dependencies.
my problem here have project structure this:
project/ |--utils | |--number_util.ts |--views | |--article_page | |-- editor_view | |--editor_text_area.ts
and when include utils/number_util
inside editor_text_area
module, import statement looks like:
import { numberutil } './../../../utils/number_util';
which long , not readable and, worst of all, difficult maintain: whenever need move editor_text_area
, have update each these relative paths, when in meantime can use non-relative way of
import { numberutil } 'utils/number_util';
does have suggestions on how best module imports achieve highest readability , maintainability?
but using non-relative way poses problem (other not recommended official docs): if installed npm
module has same name module i'm importing? on note, not safe uglier alternative mentioned above.
depending on project tooling , structure, have options.
a) publish part of dependencies stand-alone modules, perhaps in private registry. can install them npm , require them other external dependency.
b) many module systems support sort of path mapping. vue-js webpack template uses webpack's alias feature set @
source code root. typescript supports path mapping too. after introduce mapping can use
import { numberutil } '@/utils/number_util';
this approach introduces private namespace modules. safe, in ever shadow npm module name @
invalid name , therefore cannot exist.
for example, have have these entries in compileroptions
:
"baseurl": ".", "paths": { "@/*": ["*"] }
or if want import modules utils
, change mapping "@/*": ["utils/*"]
, import using '@/number_util'
.
c) thing consider improve project structure. depending on actual project, might make sense apply facade pattern @ 1 point or another. maybe inject dependency editor_text_area
instead of letting import itself.
Comments
Post a Comment