Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

import module just to run it

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 import it anywhere, I just need to ensure it runs once.

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

  2. What's the best place in a project to do this? I currently have it in my main js file where everything starts up, but that file has nothing to do with forms, or data validation, so it feels somewhat awkwared

like image 323
bigblind Avatar asked Jul 15 '16 14:07

bigblind


People also ask

Why is Python running a module when I import it?

This happens because when Python imports a module, it runs all the code in that module. After running the module it takes whatever variables were defined in that module, and it puts them on the module object, which in our case is salutations .

Can a module import itself?

There is no need for a module to import itself. A module importing itself may lead to errors as the module may be in an incomplete state when imported by itself.


1 Answers

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.

like image 160
Bergi Avatar answered Oct 01 '22 13:10

Bergi