javascript - JS npm 包,不能在模块外使用 import 语句

标签 javascript npm webpack

我想使用这个 npm 包 https://github.com/nefe/number-precision ,按照步骤操作,但不起作用。

  1. npm install number- precision --save--dep

  2. import NP from 'number-precision'require()在我的 JS 文件第一行,错误消息将如下所示: 无法定义 require && 导出不能在模块外部使用 import 语句。

  3. <script src="node_modules/number-precision/build/index.iife.js">import NP from 'number-precision </script>

    它不会显示任何错误消息,但在我的js文件中,NP方法仍然不起作用。

  4. <script src="/workout.js"></script>并将我的js文件放在第一行 import NP from 'number- precision'

    我得到了这个:

    拒绝执行来自“http://0.0.0.0:2000/node_modules/number-”的脚本 precision/' 因为它的 MIME 类型('text/html')是不可执行的,而严格的 MIME 类型 检查已启用。

    如何在我的 js 文件中正确执行这个 npm 包?

最佳答案

要在浏览器中使用导入,执行导入的文件需要

a) 包含在 type="module" 中:

<script src="./workout.js" type="module"></script>

b) 它仅适用于远程脚本(即具有 src 属性),不适用于内联脚本。

另请注意,您无法在浏览器中速记来自 node_modules 的引用文件,这仅在与 Node 一起运行时才有效。

所以,在你的锻炼.js 中,像这样开始:

import 'https://github.com/nefe/number-precision/blob/master/build/index.iife.js';

不幸的是,该库作者似乎没有提供真正的 ES6 模块版本 ( I've just opened an issue on that ),因此您无法按照页面建议的方式继续操作并将脚本导入到变量 NP 中。

不过,像上面所示的导入一样执行脚本应该适合您,并在全局命名空间中公开该库。

关于javascript - JS npm 包,不能在模块外使用 import 语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59123075/

相关文章:

node.js - 在 Ubuntu Server 20.04LTS 上全局安装 PM2 出错

react-native - 如何在 Expo 应用中集成 react-native-linear-gradient

jquery - 使用 typescript 和 webpack 扩展 jQuery

javascript - 如何正确从 gl-matrix.js 导入?

javascript - 从前端到后端再到前端发送数据

node.js - Nightmare JS : how to set cookie?

javascript - 将命令行参数发送到 npm 脚本

javascript - JSON 路径中的变量

javascript - jquery blueimp文件上传不触发

javascript - bootstrap static 固定导航栏在滚动条上跳跃