我如何将此要求作为es6导入语句编写

Joe*_*oyd 2 javascript import node.js ecmascript-6

问题

我有这个要求声明

require('smoothscroll-polyfill').polyfill();
Run Code Online (Sandbox Code Playgroud)

但我想把它写成es6 import语句

我试过了

import 'smoothscroll-polyfill';
Run Code Online (Sandbox Code Playgroud)

import * as 'smoothscrollPolyfill' from 'smoothscroll-polyfill';
Run Code Online (Sandbox Code Playgroud)

但是无法让它正常工作,那么导入这样的包的正确方法是什么?

T.J*_*der 6

你要分两部分,首先是导入,然后是函数调用:

如果polyfill它本身是一个命名导出,它不关心什么this时候被调用:

import {polyfill} from 'smoothscroll-polyfill';
polyfill();
Run Code Online (Sandbox Code Playgroud)

(而你现在已经确认是这种情况.)


为了完整起见,在确认上述内容之前,我还列出了将来可能对其他人有用的其他可能性:

如果polyfill是在一个属性默认出口(而不是它自己的命名出口),那么我们导入默认(没有{}import声明中),然后使用它的属性:

import smoothScrollPolyFill from 'smoothscroll-polyfill';
const polyfill = smoothScrollPolyFill.polyfill();
Run Code Online (Sandbox Code Playgroud)

如果该smoothScrollPolyFill部件是命名导出并且polyfill是其上的属性,那么我们将使用{}on import:

import {smoothScrollPolyFill} from 'smoothscroll-polyfill';
const polyfill = smoothScrollPolyFill.polyfill();
Run Code Online (Sandbox Code Playgroud)