如何在app.js中导入tomselect以避免浏览器错误?

发布于 2025-01-18 06:03:29 字数 1070 浏览 5 评论 0原文

我正在开发一个使用 webpack / encore 的 symfony 5.4 应用程序。我想使用 tomselect javascript 插件。我用yarn安装了它,并想以某种方式将它导入到app.js中,但它不起作用。

我在 app.js 中尝试了这种方法:

TomSelect = window.TomSelect = require('tom-select');

并且

import {TomSelect} from 'tom-select'

我总是在浏览

import TomSelect from "tom-select/dist/js/tom-select.complete.min.js";

我在 html.twig 文件中写了这个:

{% block javascripts %}
    {{ parent() }}
    <script>
        new TomSelect('select', {});
    </script>
{% endblock %}

器的 javascript 控制台中收到错误:

未捕获的引用错误:TomSelect 未定义

but if I import this way, TomSelect is work:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/tom-select/2.0.1/js/tom-select.complete.js"></script>
    <script>
        new TomSelect('select', {});
    </script>

那么我应该在 app.js 中编写什么以使 tomselect 工作?

I'm working on a symfony 5.4 application that uses webpack / encore. I want to use the tomselect javascript plugin. i installed it with yarn and want to import it somehow in app.js but it doesn't work.

I tryed this ways in app.js:

TomSelect = window.TomSelect = require('tom-select');

and

import {TomSelect} from 'tom-select'

and

import TomSelect from "tom-select/dist/js/tom-select.complete.min.js";

and I write this in the html.twig files:

{% block javascripts %}
    {{ parent() }}
    <script>
        new TomSelect('select', {});
    </script>
{% endblock %}

I always get the error in browser's javascript console:

Uncaught ReferenceError: TomSelect is not defined

but if I import this way, TomSelect is work:

    <script src="https://cdnjs.cloudflare.com/ajax/libs/tom-select/2.0.1/js/tom-select.complete.js"></script>
    <script>
        new TomSelect('select', {});
    </script>

So what should I write in app.js to make tomselect work?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

等风也等你 2025-01-25 06:03:29

有同样的问题。您需要推迟 TomSelect 对象的初始化。您的 JS 代码会在加载 app.js 之前执行。

将 TomSelect 包含到您的 app.js 包中应该可以按照您的方式工作:

window.TomSelect = require('tom-select');

然后,将您的初始化包装到 DOMContentLoaded 事件处理程序中:

document.addEventListener("DOMContentLoaded", function(event) {
  new TomSelect('select', {});
});

Having the same problem. You need to defer the initialization of your TomSelect object. Your JS code gets executed before your app.js is loaded.

Including TomSelect to your app.js bundle should work how you did it:

window.TomSelect = require('tom-select');

Then, wrap your initialization into a DOMContentLoaded event handler:

document.addEventListener("DOMContentLoaded", function(event) {
  new TomSelect('select', {});
});
混浊又暗下来 2025-01-25 06:03:29

尝试使用:

const TomSelect = require('tom-select')

Try use:

const TomSelect = require('tom-select')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文