简体   繁体   中英

Importing "regular" javascript packages installed with npm in Webpack

I've npm installed smooth-scroll , a package which does not support the import syntax.

I am sure it will work If I manually copy the source code to the libs library and use a script tag:

<script src="/libs/smooth-scroll.js"></script>

But how do I use the import syntax with it. I've tried two options and neither worked.

option A:

import scroller from 'smooth-scroll';

option B:

import {scroller} from 'smooth-scroll';

It was a guess and obviously not meant to work but how does one uses import and get Webpack to serve it?

UPDATE:

I've noticed that the package's source starts with the following line:

(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) {
...

Does this means the package already supports ES2015 import?

The simplest answer would be to go into the source code of smooth-scroll.js and to add to the bottom:

export default smoothScrollFunction;

Where smoothScrollFunction is the function / object / whatever that you're wanting to import. Then the import statement would work in other code using:

import scroller from "./lib/smooth-scroller";

That's how importing and exporting works with ES2015. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM