繁体   English   中英

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

[英]How do i write this require as an es6 import statement

问题

我有这个要求声明

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

但我想把它写成es6 import语句

我努力了

import 'smoothscroll-polyfill';

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

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

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

如果polyfill本身是一个名为出口它并不关心this是当它被称为:

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

(而且你现在已经证实了这种情况。)


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

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

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

如果smoothScrollPolyFill部分是一个名叫出口和polyfill是它的属性,然后我们会使用{}import

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM