问题
我有这份要求声明
require('smoothscroll-polyfill').polyfill();
但是我想把它写成一个es6导入语句
我试过了
import 'smoothscroll-polyfill';
和
import * as 'smoothscrollPolyfill' from 'smoothscroll-polyfill';
但是不能让它正常工作,那么导入这样一个包的正确方法是什么呢?
发布于 2017-03-03 13:18:29
您需要分两部分完成,首先是导入,然后是函数调用:
如果polyfill
本身是一个命名的导出和,那么它并不关心当它被调用时this
是什么:
import {polyfill} from 'smoothscroll-polyfill';
polyfill();
(现在你已经有了https://stackoverflow.com/questions/42579853/how-do-i-write-this-require-as-an-es6-import-statement/42579961?noredirect=1#comment72292602_42579961,情况就是这样。)
为了完整起见,在上述情况得到证实之前,我还列举了今后可能对其他人有用的其他可能性:
如果polyfill
是默认导出的属性(而不是它自己命名的导出),那么我们导入默认值( import
语句中没有{}
),然后使用它的属性:
import smoothScrollPolyFill from 'smoothscroll-polyfill';
const polyfill = smoothScrollPolyFill.polyfill();
如果smoothScrollPolyFill
部件是一个命名的导出,而polyfill
是其上的一个属性,那么我们将在import
上使用{}
import {smoothScrollPolyFill} from 'smoothscroll-polyfill';
const polyfill = smoothScrollPolyFill.polyfill();
发布于 2017-03-03 13:17:12
使用import {} from '...'
代替。
import {polyfill} from 'smoothscroll-polyfill';//ref polyfill from 'smotthscroll-polyfill'
polyfill();//ref a method,so you must call it after imported.
发布于 2017-03-03 13:17:05
假设您正在使用Babel或类似的东西来提供CommonJS模块和ES6模块之间的兼容性,那么语法如下所示:
import smoothscrollPolyfill from "smoothscroll-polyfill";
smoothscrollPolyfill.polyfill();
https://stackoverflow.com/questions/42579853
复制相似问题