How do i write this require as an es6 import state

2019-01-27 01:38发布

问题:

Problem

I have this require statement

require('smoothscroll-polyfill').polyfill();

But I would like to write it as an es6 import statement

I have tried

import 'smoothscroll-polyfill';

and

import * as 'smoothscrollPolyfill' from 'smoothscroll-polyfill';

But cant get it to work correctly, so what is the correct way to import a package like this?

回答1:

You'd do it in two parts, first the import, then the function call:

If polyfill itself is a named export and it doesn't care what this is when it's called:

import {polyfill} from 'smoothscroll-polyfill';
polyfill();

(And you've now confirmed that was the case.)


For completeness, before the above was confirmed, I also listed these other possibilities which may be useful for others in future:

If polyfill is a property on the default export (rather than its own named export), then we import the default (no {} in the import statement) and then use its property:

import smoothScrollPolyFill from 'smoothscroll-polyfill';
const polyfill = smoothScrollPolyFill.polyfill();

If the smoothScrollPolyFill part is a named export and polyfill is a property on it, then we'd use the {} on import:

import {smoothScrollPolyFill} from 'smoothscroll-polyfill';
const polyfill = smoothScrollPolyFill.polyfill();


回答2:

using import {} from '...' instead.

 import {polyfill} from 'smoothscroll-polyfill';//ref polyfill from 'smotthscroll-polyfill'
 polyfill();//ref a method,so you must call it after imported.


回答3:

Assuming you're using Babel or something similar to provide compatibility between CommonJS modules and ES6 modules, the syntax would look something like this:

import smoothscrollPolyfill from "smoothscroll-polyfill";
smoothscrollPolyfill.polyfill();