导入模块只是为了运行它 [英] import module just to run it

查看:78
本文介绍了导入模块只是为了运行它的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个JavaScript文件,用于注册我正在使用的表单验证库的验证器。这些验证器可以通过该库访问,所以我不需要在任何地方导入它,我只需要确保它运行一次。


  1. 如何在es6中以这种方式导入模块?


  2. 项目中最好的方法是什么?我目前在我的主要js文件中启动,但该文件与表单或数据验证无关,因此感觉有点awkwared



解决方案


如何在es6中以这种方式导入模块?


< blockquote>

您可以使用

  import'validators / register'; 

仅导入其副作用的模块。


项目中最好的选择是什么?


最好的解决方案是不要将验证器注册为副作用,而是使用自定义对象来装饰验证库。如果您需要使用注册方法,只需将导入到任何模块中即可。正在使用注册的验证器,通常与库自身的导入一起。如果您在许多地方需要他们,您也可以在额外的模块中将图书馆与注册捆绑在一起。


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

解决方案

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.

这篇关于导入模块只是为了运行它的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆