将 Javascript 库导入 StencilJs 的 TypeScript

Import Javascript Library Into TypeScript For StencilJs

我在我的项目中包含了以下js库: Particles.js。现在在我的组件中,我导入它并像这样加载它:

import { Component, h } from '@stencil/core';
import * as particlesJS from 'particles.js';

@Component({
    tag: 'app-home',
    styleUrl: 'app-home.css'
})
export class AppHome {

    componentDidLoad() {
        particlesJS.load('particles-js', 'assets/particlesjs-config.json', function() {
            console.log('callback - particles.js config loaded');
        });
    }

    render() {
        return (
            <div id="particles" class='app-home w-full h-full fixed bg-blue-200'>

            </div>
        );
    }
}

现在的问题是当我构建 运行 我的代码时出现以下错误:

TypeError: "undefined is not a function"

particlesJS 由于某种原因似乎总是未定义,即使我已经在顶部导入了它。

您可以使用require帮助

将js函数导入ts文件
const particlesJS = require('./particles');

但是所有函数都应该像 module.exports 在 particles.js

中导出

particles.js 不导出任何变量,而是在全局 window 对象上设置一个变量,所以你不能像这样导入它。而是尝试

import 'particles.js';

然后你可以直接从window对象访问它:

window.particlesJS.load(...)

相关问题:https://github.com/VincentGarreau/particles.js/issues/265