es6 导入副作用的含义 [英] es6 import for side effects meaning

查看:28
本文介绍了es6 导入副作用的含义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读 MDN 上的 es6 导入声明 参考.语法:

I was reading the es6 import statement reference on MDN. The syntax:

import "my-module";

将导入整个模块仅用于副作用,而不导入任何绑定.我不确定副作用是什么意思.我一直在使用 angularimport "angular".Angular 绑定到窗口但不返回对象.所以我不确定这是否会被称为副作用.

will import an entire module for side effects only, without importing any bindings. I am not sure what side effects mean. I have been using with angular by saying import "angular". Angular binds to window but does not return a object. So I am not sure if this would be called as a side effect exactly.

推荐答案

当你需要导入一些不导出任何东西但会做其他事情的东西时,这是一个只有副作用的模块.您导入它只是为了初始化它.

When you need to import something that doesn't export anything, but does something else, this is a side effect only module. You import it only to initialize it.

纯模块和非纯模块

如果您将模块视为函数,那么仅通过导出其内容来影响作用域的模块就像一个始终返回相同内容的函数(没有参数的纯函数).无论你导入 react 15.01 多少次,你总会得到一个包含相同方法的对象.

If you think about modules as functions, a module that only effects the scope by exporting it's content is like a function that always returns the same thing (a pure function without parameters). No matter how many times you'll import react 15.01, you'll always get an object that contains the same methods.

有副作用的模块是以其他方式改变作用域然后返回一些东西的模块,它的效果并不总是可预测的,并且可能会受到外力(非纯函数)的影响.例如,polyfill 可能不会做任何事情,因为它发现浏览器已经支持它启用的功能.

A module with side-effects is one that changes the scope in other ways then returning something, and it's effects are not always predictable, and can be affected by outside forces (non pure function). A polyfill for example, might not do anything, because it finds that the feature that it enables is already supported by the browser.

副作用示例:

  • Angular 绑定到全局 window 对象,但不导出任何东西.
  • 在浏览器中启用 ES6 功能的 polyfill支持它们,比如 babel polyfill 是副作用.
  • 许多 jQuery 插件将自身附加到全局 jQuery 对象.
  • 在后台运行、监控用户交互并将数据发送到服务器的分析模块.
  • 如果您不使用 CSS 模块,则在 webpack 中导入 CSS 会被视为副作用.
  • Angular binds to the global window object, but doesn't export anything.
  • A polyfill that enables ES6 features in the browsers that don't support them, like babel polyfill is a side effect.
  • Many jQuery plugins attach themselves to the global jQuery object.
  • Analytics modules that run in the background, monitor user interaction, and send the data to a server.
  • Importing CSS in webpack can be considered a side effect if you're not using CSS modules.

这篇关于es6 导入副作用的含义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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