【问题标题】:How to import a NPM package into browser's console [duplicate]如何将 NPM 包导入浏览器的控制台 [重复]
【发布时间】:2019-11-18 18:57:45
【问题描述】:

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

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: 无法使用 模块外的 import 语句

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

【问题讨论】:

标签: javascript browser-console


【解决方案1】:

您不要使用<script> 标签来导入这样的模块,或者如果您这样做,您可以在脚本本身中使用import 语句(如import * as reduxSaga from "https://unpkg.com/redux-saga@1.0.3/dist/redux-saga-effects.esmodules-browsers.js")来执行此操作。

关键是在<script>标签上设置type,这样它就知道将脚本作为模块加载(允许importexport)。

p>

例如:

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>

【讨论】:

    猜你喜欢
    • 2012-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-12
    • 1970-01-01
    • 2018-03-11
    • 2018-01-31
    相关资源
    最近更新 更多