es6 import for side effects meaning

后端 未结 3 1866
青春惊慌失措
青春惊慌失措 2020-11-30 05:34

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

import \"my-module\";

will import an entire module for side effects on

相关标签:
3条回答
  • 2020-11-30 06:01

    Consider Below as a example code. as you try to import something , it wouldn't export anything but do many things and overrides you existing code(if you have) so that's the side effect.

    import Ember from 'ember';
    Ember.RSVP.configure('onerror', function(error) {
        ....
    });
    

    app.js:

    import './overrides/extra';
    
    0 讨论(0)
  • 2020-11-30 06:06

    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.

    Pure and Non Pure Modules

    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.

    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.

    Examples of side effects:

    • 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.
    0 讨论(0)
  • 2020-11-30 06:12

    Here is an example:

    //a.js
    function print1()
    {
      console.log("export print1 is working");
    }
    
    function print2()
    {
      console.log("non-export print2 is working");
    }
    
    print1();
    print2();
    
    //b.js
    import "a.js";
    

    When you run "b.js", you will see the printed messages, which are called

    side effects

    .

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