最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How do i write this require as an es6 import statement - Stack Overflow

programmeradmin6浏览0评论

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?

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?

Share Improve this question edited Mar 3, 2017 at 13:15 m87 4,5113 gold badges18 silver badges31 bronze badges asked Mar 3, 2017 at 13:13 Joe LloydJoe Lloyd 22.5k7 gold badges58 silver badges84 bronze badges 1
  • It's hard to answer this without seeing the exports in the module you're importing. – T.J. Crowder Commented Mar 3, 2017 at 13:20
Add a ment  | 

3 Answers 3

Reset to default 7

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 pleteness, 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();

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.

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

import smoothscrollPolyfill from "smoothscroll-polyfill";
smoothscrollPolyfill.polyfill();
发布评论

评论列表(0)

  1. 暂无评论