[英]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.