Importing “regular” javascript packages installed with npm in Webpack

点点圈 提交于 2020-01-04 06:57:11

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/39813594/importing-regular-javascript-packages-installed-with-npm-in-webpack

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!