[英]How to include external javascript library in PreactJS?
我目前是一個基於preactJS和algolia的小型項目? 我發現有針對reactjs的algolia組件,但是不幸的是,沒有針對preactjs的algolia組件。 這就是為什么我的問題是如何將algolia javascript文件包含到preactjs中?
<script src="https://cdn.jsdelivr.net/instantsearch.js/1/instantsearch.min.js"></script>
Preact具有組件Head。 要安裝它運行
yarn add preact-head
這樣就可以指定標准的head元素,例如腳本,meta等。例如app.js
import Head from "preact-head";
export default class App extends Component {
render() {
return (
<div id="app">
<Head>
<meta name="Whatever" />
<script src="https://cdn.jsdelivr.net/instantsearch.js/1/instantsearch.min.js"></script>
</Head>
</div>
);
}
}
您可以動態插入腳本,請嘗試以下操作:
componentWillMount() {
const script = document.createElement("script");
script.src = "https://cdn.jsdelivr.net/instantsearch.js/1/instantsearch.min.js";
script.async = true;
script.onload = function() {
// init your algolia code here
}
document.body.appendChild(script);
},
您可以將其添加到head標簽之間的index.html中。 在React中,index.html在public/index.html
在Preact中,index.html在src/index.html
<head>
<script src="https://cdn.jsdelivr.net/instantsearch.js/1/instantsearch.min.js"></script>
</head>
您可以安裝軟件包algoliasearch (如果軟件包不正確,請在https://npmjs.com上搜索所需的軟件包)
現在您可以執行npm install algoliasearch --save
在根目錄下保存package.json並在模塊中使用它,如下所示-
import algolia from 'algolia';
然后在您的代碼中使用其方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.