2017-03-03 59 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.