[英]How to import TomSelect in App.js to avoid browser error?
I'm working on a symfony 5.4 application that uses webpack / encore.我正在开发一个使用 webpack / encore 的 symfony 5.4 应用程序。 I want to use the tomselect javascript plugin.
我想使用tomselect javascript 插件。 i installed it with yarn and want to import it somehow in app.js but it doesn't work.
我用 yarn 安装了它,想以某种方式在 app.js 中导入它,但它不起作用。
I tryed this ways in app.js:我在 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:我把它写在 html.twig 文件中:
{% block javascripts %}
{{ parent() }}
<script>
new TomSelect('select', {});
</script>
{% endblock %}
I always get the error in browser's javascript console:我总是在浏览器的 javascript 控制台中收到错误消息:
Uncaught ReferenceError: TomSelect is not defined
未捕获的 ReferenceError:未定义 TomSelect
but if I import this way, TomSelect is work:但如果我以这种方式导入,TomSelect 就可以了:
<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?那么我应该在 app.js 中写些什么来让 tomselect 工作呢?
Having the same problem.有同样的问题。 You need to defer the initialization of your TomSelect object.
您需要推迟 TomSelect 对象的初始化。 Your JS code gets executed before your app.js is loaded.
你的 JS 代码在你的 app.js 被加载之前被执行。
Including TomSelect to your app.js bundle should work how you did it:将 TomSelect 包含到您的 app.js 包中应该可以按照您的方式工作:
window.TomSelect = require('tom-select');
Then, wrap your initialization into a DOMContentLoaded event handler:然后,将初始化包装到 DOMContentLoaded 事件处理程序中:
document.addEventListener("DOMContentLoaded", function(event) {
new TomSelect('select', {});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.