繁体   English   中英

如何将 npm 包导入客户端文件

[英]How to import npm package to a client file

我正在尝试将js-search npm 包导入到我的客户端.js文件中。 他们的文档说import * as JsSearch from 'js-search';编写import * as JsSearch from 'js-search'; ,但是,这给了我一个Uncaught TypeError: Failed to resolve module specifier "js-search". Relative references must start with either "/", "./", or "../". Uncaught TypeError: Failed to resolve module specifier "js-search". Relative references must start with either "/", "./", or "../". . 我尝试配置了很长时间的相对路径,但我终于发现'js-search'指的是包名,而不是目录。 那么,我一定缺少一些允许我使用此导入行的依赖项吗? 谢谢你。

编辑:目录结构:

myproject
├── myproject
├── node_modules\js-search
└── myapp
    ├── static\myapp
    │            └── myapp.js
    └── templates\search
                    └── index.html

编辑:可能是因为我在 localhost 而不是服务器上运行?

您使用的 NPM 包可能是为 node.js 代码制作的包。 import * as JsSearch from 'js-search'; line 用于 node.js,在浏览器中不能单独工作。

要在浏览器中运行这些类型的包,您基本上需要使用转译器对其进行转换。 最常见的可能是 webpack。

有时,软件包还包含专门针对浏览器的预构建或缩小版本。 如果是这种情况,您可能会在js-search目录中找到类似something.min.js的文件。

js-search看起来可能有这个,因为我在他们的存储库中看到了一个汇总配置文件。 Rollup 是 webpack 的替代品。

如果不是这种情况,不幸的是,您必须进入构建工具这一非常疯狂的兔子洞。

您必须使用type="module"链接myapp.js文件,如下所示

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

然后在myapp.js您必须使用来自node_modules相对路径导入js-search ,因为您没有使用任何像 webpack 这样的打包器。 在您的myapp.js文件中,您可以使用如下所示的js-search

import * as JsSearch from './node_modules/js-search/dist/esm/js-search.js';

var theGreatGatsby = {
  isbn: '9781597226769',
  title: 'The Great Gatsby',
  author: {
    name: 'F. Scott Fitzgerald'
  },
  tags: ['book', 'inspirational']
};
var theDaVinciCode = {
  isbn: '0307474275',
  title: 'The DaVinci Code',
  author: {
    name: 'Dan Brown'
  },
  tags: ['book', 'mystery']
};
var angelsAndDemons = {
  isbn: '074349346X',
  title: 'Angels & Demons',
  author: {
    name: 'Dan Brown',
  },
  tags: ['book', 'mystery']
};

var search = new JsSearch.Search('isbn');
search.addIndex('title');
search.addIndex(['author', 'name']);
search.addIndex('tags')

search.addDocuments([theGreatGatsby, theDaVinciCode, angelsAndDemons]);

console.log(search.search('The'));    // [theGreatGatsby, theDaVinciCode]
console.log(search.search('scott'));  // [theGreatGatsby]
console.log(search.search('dan'));    // [angelsAndDemons, theDaVinciCode]
console.log(search.search('mystery')); // [angelsAndDemons, theDaVinciCode]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM