2

The package smooth-scroll does not support ES2015 import. I want to offer a pull request with support for import.

According to the docs I need to add the following line:

export default smoothScrollFunction;

However the package start with a self-invoking method and I am not sure how to proceed? How do you export a self invoking method?

code:

(function (root, factory) {
    if ( typeof define === 'function' && define.amd ) {
        define([], factory(root));
    } else if ( typeof exports === 'object' ) {
        module.exports = factory(root);
    } else {
        root.smoothScroll = factory(root);
    }
})(typeof global !== 'undefined' ? global : this.window || this.global, (function (root) {

    'use strict';

    //
    // more code...
    //
Guy
  • 12,488
  • 16
  • 79
  • 119

1 Answers1

3

ES2015 import/export statements require transpilation as no environment currently supports them. When transpiled they will be transformed into something that is supported by the target environment. If your target is Node this means that export statements would become module.exports = ..., or if your target is the browser then your modules will likely be bundled and wrapped in such a way that they are require-able, e.g. as in Browserify and Webpack.

Does it mean it's ES2015 import ready?

Practically, yes. Modules do not need to use the import/export in order to be ES2015 import friendly because actually no environment is, we just transform the import/export syntax in a way that makes it compatible.

In particular, with the module you have shared, you can import smoothScrollFunction from 'smooth-scroll' without the module itself containing an export smoothScrollFunction statement, as your import statement will be transpiled to (something like) var smoothScrollFunction = require('smooth-scroll') anyway.

Having said all this, in order to address the question in its entirety, you would amend an IIFE1 to be strictly ES2015 import compatible by removing the IIFE altogether, as ES2015 modules are standalone and have their own scope, much like modules in Node. You would however be dropping support for browsers, which undermines the purpose of using the IIFE / UMD2 approach.

For example (remember that this is not actually necessary!), we would take whatever the return value of the factory function is, along with anything that occurs before it, and move this out of the factory function. We would then export default the return value of the factory function.

// Anything before the return statement 
// in the factory function goes here

export default // Return value of factory function goes here

1IIFE: immediately invoked function expression

2UMD: universal module declaration

sdgluck
  • 24,894
  • 8
  • 75
  • 90
  • You could however transpile `export` declaration back to UMD using a build tool such as rollup – Bergi Oct 03 '16 at 13:02