Home > Software design >  How to move reusable JavaScript code in separate file, than the main and use it several times?
How to move reusable JavaScript code in separate file, than the main and use it several times?

Time:07-02

I have a DataTable with a lot of properties. Every time I want to use it, I have to copy all of them. It makes my view's code behind a huge mess. So I decide to create a separate .js file and copy the reusable code there but I can not reference it in my main file. Some part of my .js code is like bellow:

      function loadDataTable() {

        $(".yadcf-filter-range-date").persianDatepicker();
        dataTable = $('#SP1').DataTable({
            serverSide: true,
            processing: true,
            pageLength: 10,
            infoFiltered: true,
            orderMulti: false,
            scrollX: true,
            scrollY: true,
            bStateSave: true,
            columnDefs: [{ orderable: false, targets: [15] }],
             .
             .
             .
       }

I create a function in another js file for example like bellow:

    function CommonPart(i) { 
            serverSide: true,
            processing: true,
            pageLength: 10,
            infoFiltered: true,
            orderMulti: false,
            scrollX: true,
            scrollY: true,
            bStateSave: true,
            columnDefs: [{ orderable: false, targets: [i] }]
           }

I do not know how to use CommonPart in my main code for example like bellow:

      function loadDataTable() {

        $(".yadcf-filter-range-date").persianDatepicker();
        dataTable = $('#SP1').DataTable({
        CommonPart(15);
        ...
         });

CodePudding user response:

My preferred way to accomplish this is with ECMAscript modules.

You can place each of those functions into a separate file. You can name the files what every you like, but I usually name them after the function it contains. For web, I'd give the file a .js file extension. In node, I'd give it a .mjs extension.

In each file, prepend export on each function like this:

export function funcName()
{
}

Then from your main code file, you can import your functions from those separate files like this:

import { funcName } from "./fileName.mjs";

After this, you can use the functions as if they were declared in your main code file (because they are now imported).

CodePudding user response:

The best and most trusted resource id MDN webdocs link: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Modules

if you are still confused feel free to ask question..

  • Related