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

时间:2017-03-03 13:13:26

标签: javascript node.js import ecmascript-6

问题

我有这个要求声明

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

但我想把它写成es6导入语句

我试过了

import 'smoothscroll-polyfill';

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

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

3 个答案:

答案 0 :(得分:6)

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

如果polyfill本身是指定的导出,那么在调用时this并不关心:

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

(你现在confirmed就是这种情况。)

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

如果polyfill默认导出的属性(而不是其自己的命名导出),那么我们会导入{{1}中的默认值{} }语句然后使用其属性:

import

如果import smoothScrollPolyFill from 'smoothscroll-polyfill'; const polyfill = smoothScrollPolyFill.polyfill(); 部分是名为的导出而smoothScrollPolyFill是其中的属性,那么我们会在polyfill上使用{} }:

import

答案 1 :(得分:3)

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

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

答案 2 :(得分:1)

假设您正在使用Babel或类似的东西来提供CommonJS模块和ES6模块之间的兼容性,语法将如下所示:

import smoothscrollPolyfill from "smoothscroll-polyfill";
smoothscrollPolyfill.polyfill();
相关问题