Wie man benutzerdefinierte Javascript in Magento 2 mit requireJS hinzufügen?

How To Add Custom Javascript In Magento 2 With RequireJS

Erstellen Sie ein neues Modul mit Bay20_Bay20CustomJS

Schritt 1: Erstellen Sie die Datei registration.php.

app/code/Bay20/Bay20CustomJS/registration.php

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
	\Magento\Framework\Component\ComponentRegistrar::MODULE,
	'Bay20_Bay20CustomJS',
	__DIR__
);

Schritt 2: Erstellen Sie die Datei module.xml.

app/code/Bay20/Bay20CustomJS/etc/module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Bay20_Bay20CustomJS" setup_version="1.0.0">
    </module>
</config>

Schritt 3: Erstellen Sie die Datei requirejs-config.js.

app/code/Bay20/Bay20CustomJS/view/frontend/requirejs-config.js

var config = {
    map: {
        '*': {
            wktestrequire: 'Bay20_Bay20CustomJS/js/wkrequirejs',
        }
    }
};

Schritt 4: Datei test.phtml erstellen

app/code/Bay20/Bay20CustomJS/view/frontend/templates/test.phtml

<div id="testdiv">
	<a>Test anchor tag</a>
</div>

<?php
$formData = [
    'divElement'       =>  '#testdiv',
];
$serializedFormData = $this->helper('Magento\Framework\Json\Helper\Data')->jsonEncode($formData);
?>
<script type="text/x-magento-init">
    {
        "*": {
            "wktestrequire": <?php /* @noEscape */ echo $serializedFormData; ?>
        }
    }
</script>

Schritt 5: Erstellen Sie die Datei wkrequirejs.js.

app/code/Bay20/Bay20CustomJS/view/frontend/web/js/wkrequirejs.js

define([
    "jquery",
    'Magento_Ui/js/modal/alert',
    "jquery/ui",
], function ($, alert) {
    'use strict';
    $.widget('mage.wktestrequire', {
        options: {
            confirmMsg: ('divElement is removed.')
        },
        _create: function () {
            var self = this;
            $(self.options.divElement).remove();
            alert({
                content: self.options.confirmMsg
            });
        }
    });
    return $.mage.wktestrequire;
});

Schritt 6: Führen Sie den folgenden Befehl aus.

php bin/magento setup:upgrade

Bitte kontaktieren Sie uns unter manish@bay20.com oder rufen Sie uns unter +91-8800519180 an, wenn Sie Unterstützung für Magento 2 benötigen. Sie können auch die Magento2-Entwicklungsseite besuchen, um die von uns angebotenen Dienstleistungen zu überprüfen.