Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Importing a self invoking function

I have created a particular effect and wrapped it into a self-invoking function in myEffect.js file,

(function () {
    // yada yada...
}());

Is it possible to then use the es6 way of importing to import this into my main file so that it will run as it is? Reason I'm doing this is my main js file has other misc stuff and this effect is pretty long in itself and I'm hoping to be able to split things up.

like image 843
Kelvin Zhao Avatar asked Oct 23 '17 10:10

Kelvin Zhao


People also ask

What is a self-invoking function?

Self-Invoking function is a type of function that is invoked or called automatically after its definition when followed by the parentheses set () and primarily used for the initialization tasks.

Can you import a function in JavaScript?

The import/export syntax is called JavaScript modules. In order to be able to import a function from a different file, it has to be exported using a named or default export.

How do you import a function in HTML?

HTML imports use the <link> element to reference the file that you wish to import; this works in a similar way to how you include stylesheets. Make sure that you set the rel attribute to import to indicate to the browser that the referenced file should be imported into the document.

What are self-invoking functions explain with example?

A self-invoking (also called self-executing) function is a nameless (anonymous) function that is invoked immediately after its definition. An anonymous function is enclosed inside a set of parentheses followed by another set of parentheses () , which does the execution. (function(){ console. log(Math.


1 Answers

The effect will run when the module is evaluated, which happens when it is imported at least once in some other module.

You don't need an IIFE at all, ES6 modules already provide their own scope.

You don't need to export anything, as all your module is supposed to do is execute the side effect. It does not have a result value. (Which could be considered a design flaw, but let's not discuss that).

All you need to do is

// myEffect.js
… // yada yada

// main.js
import 'myEffect.js';
like image 196
Bergi Avatar answered Oct 09 '22 05:10

Bergi