2

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 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

That's good to know. However this means "npm install" won't work when I setup the project on a fresh computer. Voting up though! thanks
You can make an install script that puts the export line at the end of the file and put it into scripts in package.json so you can use npm run whatever (whatever being the name you give the script in scripts), either that or send in a pull request to the maintainer of smooth-scroll to add support for ES2015 import/export support.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.