Skip to main content
4 of 5
added 619 characters in body
Black
  • 3.4k
  • 4
  • 40
  • 123

Magento 2 - Create simple hello world script with UiComponent

I try to create my own Component and reuse it. So I created these files:

THEME = app\design\frontend\company\fresh

Component File:

THEME\web\js\elements\custom\input_number.js

define([
  "jquery",
  "uiComponent"
], 
function($, Component) {
  "use strict";

    return Component.extend({
        
        initialize: function () {
            return this._super();
        },
        
        test: function()
        {
            console.log("Hello world!");
        }
    });
});

requirejs-config.js:

THEME\requirejs-config.js

var config = {
    paths: {
        inputNumber: 'js/elements/custom/input_number'
    },
};

Using the new component:

THEME\Magento_Checkout\web\js\view\minicart.js

I copied the file from vendor into my theme so that I can make changes. Now I try to use my component and call my test method:

define([
    'uiComponent',
    'Magento_Customer/js/customer-data',
    'jquery',
    'ko',
    'underscore',
    'sidebar',
    'mage/translate',
    'mage/dropdown',
    'inputNumber'
], function (Component, customerData, $, ko, _, inputNumber) {
    'use strict';

    inputNumber.test();    // [ERROR] Failed to load the "Magento_Checkout/js/view/minicart" component.`

    ...

I also tried to fix the parameter order like Jorge Henrique explained:

define([
    'uiComponent',
    'Magento_Customer/js/customer-data',
    'jquery',
    'ko',
    'underscore',
    'inputNumber',
    'sidebar',
    'mage/translate',
    'mage/dropdown'
], function (Component, customerData, $, ko, _, inputNumber) {
    'use strict';

    inputNumber.test();    // [ERROR] Failed to load the "Magento_Checkout/js/view/minicart" component.`

    ...

But I still get this error in the console [ERROR] Failed to load the "Magento_Checkout/js/view/minicart" component.


I also tried to call the method inside of the method initSidebar but then I get Uncaught TypeError: inputNumber.test is not a function

THEME\Magento_Checkout\web\js\view\minicart.js:

define([
    'uiComponent',
    'Magento_Customer/js/customer-data',
    'jquery',
    'ko',
    'underscore',
    'inputNumber',
    'sidebar',
    'mage/translate',
    'mage/dropdown'
], function (Component, customerData, $, ko, _, inputNumber) {
    'use strict';
    
    var sidebarInitialized = false,
        addToCartCalls = 0,
        miniCart;

    miniCart = $("#minicart");

    function initSidebar()
    {
        inputNumber.test();  // Uncaught TypeError: inputNumber.test is not a function

        ...
Black
  • 3.4k
  • 4
  • 40
  • 123