2017-03-03 28 views
1

問題

我有這個需要聲明我如何寫這個要求作爲一個ES6 import語句

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

但我想將它寫爲ES6 import語句

我曾嘗試

import 'smoothscroll-polyfill'; 

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

但無法讓它正常工作,那麼導入這樣一個包的正確方法是什麼?

+0

很難回答沒有看到要導入的模塊中的出口。 –

回答

5

你會做兩個部分,首先是進口,那麼函數調用:

如果polyfill本身是一個名叫出口它並不關心什麼this是當它被稱爲:

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

(你現在已經confirmed是這樣的話。)


對於完整性,確認上述前,我還列出可能對他人有用的將來,這些其它的可能性:

如果polyfill是在默認出口(而不是其自身的屬性命名爲出口),那麼我們導入默認(在import聲明沒有{}),然後使用它的屬性:

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

如果smoothScrollPolyFill部分是名爲出口polyfill是它的屬性,那麼我們應該使用{}import

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

'從'smoothscroll-polyfill'中導入{polyfill};'像魅力一樣工作。感謝您的解釋。 –

+0

@JoeLloyd:很高興幫助。 –

1

假設你正在使用巴貝爾或類似提供CommonJS的模塊和模塊ES6之間的兼容性的東西,語法將是這個樣子:

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

使用import {} from '...'代替。

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