如何在 PreactJS 中包含外部 javascript 库?

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>

您可以动态插入脚本,试试这个:

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);
},

您可以将其添加到您的 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>

Preact 有组件 Head。安装它 运行

yarn add preact-head

然后就可以指定标准的头元素,如脚本、元等。E.x。 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>
            );
        }
    }

您可以安装包 algoliasearch (if package is not correct, just search the desired package at https://npmjs.com)

现在您可以在 package.json 所在的根级别执行 npm install algoliasearch --save 并在您的模块中使用它,如下所示 -

import algolia from 'algolia';

然后在您的代码中使用它的方法。