import module just to run it

后端 未结 2 585
梦如初夏
梦如初夏 2021-01-18 06:18

I have a JavaScript file that registers validators for a form validation library I\'m using. These validators become accessible through that library, so I don\'t need to imp

相关标签:
2条回答
  • 2021-01-18 06:48

    How do I import a module in such a way in es6?

    You can use

    import 'validators/register';
    

    to import a module for its side effects only.

    What's the best place in a project to do this?

    The best solution would be not to register validators as a side effect, but rather decorate the validation library with the custom objects. The module structure, i.e. where to import these decorations, then soon becomes obvious.

    If you need to use a registration approach, just put the import in any of the modules that are using the registered validators, typically alongside the import of the library itself. You can also factor this out in an extra module that bundles the library with the registrations if you need them together in many places.

    0 讨论(0)
  • 2021-01-18 06:54

    It depends on the context, are you working on Node.JS? If so, there's a [caching native feature] (https://nodejs.org/docs/latest/api/modules.html#modules_caching) that allows to cache the JS file the first time is invoked, no matter how many times is written. if not you could create a Singleton using closures. That will make sure it just runs once.

    1: es6 way

    import lib from './lib';
    

    2: you could leave it on main.js, but if it feels awkward, put it in a separate util JS file and import that one.

    0 讨论(0)
提交回复
热议问题