1

I am trying to implement selectize.js inside my project with webpack and typescript.

First I installed selectize.js and related types:

yarn add @selectize/selectize 
yarn add @types/select2 

In my code I inserted this:

require("selectize")();

jQuery(function($){

    $(document).ready(function(){

        $('.classic-select').selectize();
    
    });
    
});

The code compiles correctly but when I go to run it in console I get this error and I don't understand what it refers to:

Cannot read properties of undefined (reading '0')

Can you help me solve this problem?

Thanks in advance Danilo

2
  • By "run in the console", do you mean "run a command that starts a web server and look at the result in the browser"? Commented Jul 15, 2022 at 9:28
  • Hi @ChrisG Thank you for your reply. I mean to open the html page in the browser and verify that the code is interpreted correctly. Commented Jul 15, 2022 at 9:52

1 Answer 1

1

After several attempts, I figured out how to correctly implement selectize.

First I imported jquery and selectize like this:

import $ from 'jquery';
import 'selectize'; // globally assign select2 fn to $ element

Next I used selectize

jQuery(function($){

    $(document).ready(function(){

        (<any>$('.classic-select')).selectize();
    
    });
    
});

You can also implement it like this

$(() => {
    (<any>$('.classic-select')).selectize();
});

If you compile the code the jquery library will also be imported. If jquery has already been called in your code you can exclude it from compiling through webpack:

externals: {
  jquery: 'jQuery'
}

I hope it will be useful!

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! it's working for me. Now I'm trying to use a plugin by importing it after selectize: import "selectize-plugin-a11y"; and having this error "Uncaught ReferenceError: Selectize is not defined" from the plugin js. Could you advise?
Hi @Khoait, I'm very sorry for only responding now but I really didn't see your comment. In your webpack configuration you should make these changes: Add this : const webpack = require('webpack'); in plugins section add: new webpack.ProvidePlugin({ $: 'jquery', jQuery: 'jquery', 'window.jQuery': 'jquery', 'window.$': 'jquery' }) I solved it this way with some select2 plugins.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.