V2: no side effects when importing a module

V2: no side effects when importing a module

tacman1123tacman1123 Posts: 198Questions: 46Answers: 1
edited November 2023 in Free community support

If I understand the plugins correctly, importing a library modifies the jquery object. Since you can't conditionally import a module, it's very difficult to conditionally add the styles.

Support I want to initialize a datatable through a custom class, myDatatable(element, style), where style is bs4, bs5 or tailwind.

let style = 'bs5';
import DataTables from 'datatables.net-' + style; // doesn't work

import DataTables from 'datatables.net-bs5'
import 'datatables.net-select';

// doesn't work, can't wrap an import in an "if" statement
if (style == 'bs5') {
    import 'datatables.net-select-bs5';
}

I think one solution is to import all the plugins and styles, but require the developer to explicitly add the plugin, e.g.

import select-bs5 from 'datatables.net-select-bs5';
import select-bs4 from 'datatables.net-select-bs4';

dt = new DataTable(element);
if (style == 'bs4') {
    dt.addPlugin(select-bs4);
}

I think this is the pattern for the localization modules.

In general, I think it'd be better if the import statement had no side effects, and simply made the underlying module available.

Answers

  • allanallan Posts: 62,990Questions: 1Answers: 10,367 Site admin

    I see - you are proposing this as something that should be added for v2 rather than having built the branch code and are actually using it?

    Dynamic importing is actually coming in Javascript, so it will be possible in future.

    It would be a major breaking change to do as you propose, and although v2 would be the time to make such a change, I think the ability to change style dynamically has been requested so few times (this is the first that I recall) that it isn't a breaking change I want to make at the moment. Sorry.

    Allan

  • tacman1123tacman1123 Posts: 198Questions: 46Answers: 1

    Dynamic importing is actually coming in Javascript, so it will be possible in future.

    Oh, that'd be great!

    Right now, I'm importing everything (scroller, select, searchpanes, buttons, etc.) and simply limiting my bundle to bootstrap 5. But as you've noted with in other posts, I shouldn't have both scroller and variable-sized rows. But I don't know if it's even possible to have a single package and selectively load those plugins.

    The AssetMapper problem has been fixed, so now I'm able to import multiple packages. Tomorrow I hope to post some public examples of configuring datatables in twig without any custom javascript.

Sign In or Register to comment.