简体   繁体   English

Webpack Encore select2 不工作,没有函数导入错误

[英]Webpack Encore select2 not working with not a function import error

Using Symfony 4 and Webpack Encore , I can't get Select2 to work.使用Symfony 4Webpack Encore ,我无法让Select2工作。

I'm using select2@4.0.3 and importing it this way in app.js :我正在使用select2@4.0.3并在app.js这种方式导入:

import $  from 'jquery';
import 'bootstrap';
import 'select2';

I also tried to use我也尝试使用

Encore.autoProvidejQuery()

in webpack.config.js , then taking care of commenting thewebpack.config.js ,然后注意注释

import $ from 'jquery';

line in app.js so that jquery is not imported twice. app.js一行,以便 jquery 不会被导入两次。

I tried everything I could find in other answsers like:我尝试了在其他答案中可以找到的所有内容,例如:

import select2 form 'select2';

$(() => {
  $('.select2-enable').select2();
});

or或者

select2($);

Almost all my attempts result in the same error:我几乎所有的尝试都会导致相同的错误:

TypeError: $(...).select2 is not a function类型错误:$(...).select2 不是函数

EDIT:编辑:

Working now.现在工作。 Everytime I made a change in app.js (and rebuilt) I used the firefox devtool console to check if it was working but I always got the每次我对app.js进行更改(并重新构建)时,我都会使用 firefox devtool 控制台来检查它是否正常工作,但我总是得到

not a function不是函数

error even though the problem was solved and select2 was working.即使问题已解决并且 select2 正在工作,也会出错。

Is this because I'm using Webpack that the browser console doesn't recognize the select2() function anymore?这是因为我使用 Webpack 浏览器控制台不再识别select2()函数了吗?

First install it using yarn :首先使用yarn安装它:

yarn add select2

Then use it with require instead of import :然后将它与require而不是import

require('select2')

at your app.js file.在您的app.js文件中。

It works the same using require or import.使用 require 或 import 的工作原理相同。

Babel converts import and export declaration to CommonJS (require) which lets you load modules dynamically. Babel 将导入和导出声明转换为 CommonJS(需要),让您可以动态加载模块。

So, despite of them looking the same, try to always use require.因此,尽管它们看起来相同,但请尝试始终使用 require。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM