How to use custom function in another js file?

It is my common.js

    import Noty from "noty/lib/noty.min";
    import mojs from "mo-js/build/mo.min";

    export default {
    init() {
        // JavaScript to be fired on all pages

        // Alert function
        function themeAlert($type = 'success', $text = 'Sample Text') {// eslint-disable-line no-unused-vars
            new Noty();
            new mojs();
        }
    },
    finalize() {
        // JavaScript to be fired on all pages, after page specific JS is fired

        // Menu toggle
        $('.hamburger').click(function () {
            $(this).toggleClass('is-active');
        });
    },
    };

And it is single.js

    export default {
    init() {
        // JavaScript to be fired on the about us page

        // Alert function
        themeAlert();
    },

    finalize() {
        // scripts here fire after init() runs
    },
    };

But i got console error. Can’t use themeAlaer() function in global.

If you want to import a function from another file, you would need to precede it with an export statement. Also, I would define it outside your default object in common.js.

export const themeAlert = function ($type = 'success', $text = 'Sample Text') { // eslint-disable-line no-unused-vars
  new Noty();
  new mojs();
}

export default {
  init() {
    // ...
  }, // ...

in single.js

import { themeAlert } from './common.js'

export default {
  init() {
    themeAlert()
  },
}
1 Like

Thank you. It solved my problem. I want to ask what different between

import { themeAlert } from './common.js'

and

import themeAlert from './common.js'

No problem! I am glad you got it working.

Without the curly brackets, you would import what corresponds to your default export in common.js (export default {}).

The brackets specifies a named export (export const themeAlert).

You can read a bit about it on MDN web docs. Here for import and here for export.

2 Likes