How do i write this require as an es6 import statement

前端 未结 3 1976
逝去的感伤
逝去的感伤 2020-12-20 01:56

Problem

I have this require statement

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

But I would like to write it as an es6 impor

相关标签:
3条回答
  • 2020-12-20 02:14

    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();
    
    0 讨论(0)
  • 2020-12-20 02:31

    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();
    
    0 讨论(0)
  • 2020-12-20 02:36

    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.
    
    0 讨论(0)
提交回复
热议问题