Skip to content

在浏览器中直接使用npm包

仲灏2021-12-16约 1 分钟

<div style="display: none;" hidden="true" aria-hidden="true" data-nosnippet>Are you an LLM? You can read better optimized documentation at /pages/622cd4.md for this page in Markdown format</div>

很多时候我门使用一个npm测试语句往往很麻烦,需要下载,引入一些步骤,如果不符合需求的还得移除这个包

现在可以在浏览器中直接使用了 npmInstall('moment')的方式在控制台进行调试

如 qs(具有一些附加安全性的查询字符串解析和字符串化库) 这个插件

  • 先初始化这个方法

    • js
      // 存储原始传入的名称
      let pkg_name_origin = null;
      const npmInstall = (originName) => {
        // Trim string
        const name = originName.trim();
        pkg_name_origin = name;
        // 三种引入方式
        // 如果是一个有效的URL,直接通过<script />标签插入
        if (/^https?:\/\//.test(name)) return injectScript(name);
        // 如果指定了版本,尝试使用unpkg加载
        if (name.indexOf('@') !== -1) return unpkg(name);
        // 否则,尝试使用cdnjs搜索
        return cdnjs(name);
      };
      
      // 在页面中插入<script />标签
      const injectScript = (url) => {
        const script = document.createElement('script');
        script.src = url;
        script.onload = () => {
          console.log(pkg_name_origin, ' 安装成功。');
        };
        script.onerror = () => {
          console.log(pkg_name_origin, ' 安装失败。');
        };
        document.body.appendChild(script);
        // document.body.removeChild(script);
      };
      
      const unpkg = (name) => {
        injectScript(`https://unpkg.com/${name}`);
      };
      
      const cdnjs = async (name) => {
        const searchPromise = await fetch(
          `https://api.cdnjs.com/libraries?search=${name}`,
          // 不显示referrer的任何信息在请求头中
          { referrerPolicy: 'no-referrer' }
        );
        const { results, total } = await searchPromise.json();
        if (total === 0) {
          console.error('Sorry, ', name, ' not found, please try another keyword.');
          return;
        }
      
        // 取结果中最相关的一条
        const { name: exactName, latest: url } = results[0];
        if (name !== exactName) {
          console.log(name, ' not found, import ', exactName, ' instead.');
        }
        // 通过<script />标签插入
        injectScript(url);
      };
    • 如果不想每次都引用这个方法可以使用chrome插件

      • img
  • 在浏览器中控制台引入

    • npmInstall('qs') 或者使用插件的方式$i('qs')
    • image-20211216141438409
  • 测试使用, 我门调取一个qs api, 这里是使用Qs的变量

    • image-20211216142117167