[英]How to include external javascript library in PreactJS?
I'm currently one small project based on preactJS with algolia? 我目前是一个基于preactJS和algolia的小型项目? I found that there is algolia component for reactjs but unfortunately, no algolia component for preactjs.
我发现有针对reactjs的algolia组件,但是不幸的是,没有针对preactjs的algolia组件。 That's why my problem is how can I include algolia javascript file into preactjs?
这就是为什么我的问题是如何将algolia javascript文件包含到preactjs中?
<script src="https://cdn.jsdelivr.net/instantsearch.js/1/instantsearch.min.js"></script>
Preact has component Head. Preact具有组件Head。 To install it run
要安装它运行
yarn add preact-head
Then it will be possible to specify standard head element such as script, meta, etc.. Ex app.js 这样就可以指定标准的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>
);
}
}
You can insert script dynamically, try this one: 您可以动态插入脚本,请尝试以下操作:
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);
},
You can just add it in your index.html between the head tags. 您可以将其添加到head标签之间的index.html中。 In React, the index.html is in
public/index.html
In Preact, index.html is in src/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>
You can install the package algoliasearch (if package is not correct, just search the desired package at https://npmjs.com ) 您可以安装软件包algoliasearch (如果软件包不正确,请在https://npmjs.com上搜索所需的软件包)
Now you can do npm install algoliasearch --save
at your root level where package.json is there and use it in your module like following - 现在您可以执行
npm install algoliasearch --save
在根目录下保存package.json并在模块中使用它,如下所示-
import algolia from 'algolia';
And then use its methods in your code. 然后在您的代码中使用其方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.