导入“常规”在webpack中安装了npm的javascript包 [英] Importing "regular" javascript packages installed with npm in Webpack

查看:126
本文介绍了导入“常规”在webpack中安装了npm的javascript包的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经安装了npm 平滑滚动,一个不支持导入语法

I've npm installed smooth-scroll, a package which does not support the import syntax.

我确定它会工作如果我手动将源代码复制到libs库并使用脚本标签:

I am sure it will work If I manually copy the source code to the libs library and use a script tag:

<script src="/libs/smooth-scroll.js"></script>

但是如何使用导入语法。我尝试了两个选项,没有工作。

But how do I use the import syntax with it. I've tried two options and neither worked.

选项A:

import scroller from 'smooth-scroll';

选项B:

import {scroller} from 'smooth-scroll';

这是一个猜测,显然不是要工作,但是如何使用 import 并让Webpack服务?

It was a guess and obviously not meant to work but how does one uses import and get Webpack to serve it?

更新:

注意到包的源码从以下行开始:

I've noticed that the package's source starts with the following line:

(function (root, factory) {
    if ( typeof define === 'function' && define.amd ) {
        define([], factory(root));
    } else if ( typeof exports === 'object' ) {
        module.exports = factory(root);
    } else {
        root.smoothScroll = factory(root);
    }
})(typeof global !== 'undefined' ? global : this.window || this.global, (function (root) {
...

这是否意味着该包已经支持ES2015导入?

Does this means the package already supports ES2015 import?

推荐答案

最简单的答案是进入smooth-scroll.js的源代码,并添加到底部:

The simplest answer would be to go into the source code of smooth-scroll.js and to add to the bottom:

export default smoothScrollFunction;

其中smoothScrollFunction是函数/对象/您想要导入的任何内容。然后,import语句将在其他代码中使用:

Where smoothScrollFunction is the function / object / whatever that you're wanting to import. Then the import statement would work in other code using:

import scroller from "./lib/smooth-scroller";

这是导入和导出与ES2015一起使用的方式。 https://developer.mozilla.org/en-US / docs / Web / JavaScript / Reference /语句/导出

That's how importing and exporting works with ES2015. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export

这篇关于导入“常规”在webpack中安装了npm的javascript包的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆