gpt4 book ai didi

javascript - 如何将 NPM 包导入浏览器控制台

转载 作者:行者123 更新时间:2023-12-02 22:30:30 25 4
gpt4 key购买 nike

只是为了玩一些包函数,我想将其导入到浏览器的控制台中。我已经尝试过这种方法,但它给出了解析错误。

var script = document.createElement('script');
script.type = 'text/javascript';
script.src = 'https://unpkg.com/libphonenumber-js@1.7.26/core/index.js';
document.head.appendChild(script);

我遇到的错误,

parsePhoneNumberFromString.js:1 Uncaught SyntaxError: Cannot use import statement outside a module

我正在尝试使用parsePhoneNumberFromString函数进入我的浏览器控制台。

最佳答案

您不使用<script>标签来导入类似的模块,或者如果你这样做,你可以在脚本本身中使用 import 来完成它类似 import * as reduxSaga from "https://unpkg.com/redux-saga@1.0.3/dist/redux-saga-effects.esmodules-browsers.js" 的声明.

关键是设置 type 关于<script>标记为 type="module"这样它就知道将脚本作为模块加载(允许 import export )。

例如:

index.js

import {parsePhoneNumberFromString} from "https://unpkg.com/libphonenumber-js@1.7.26/core/index.js";

const pnStr = "555-555-5555";
const pn = parsePhoneNumberFromString(pnStr);
console.log(pn);

index.html

<html>
<head>
<script src="index.js" type="module"></script>
</head>
</html>

关于javascript - 如何将 NPM 包导入浏览器控制台,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58921161/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com