Magento2中使用自定义JavaScript

更新

概述

本主题讨论了如何使用自定义 JavaScript 组件与 Magento 提供的组件或自定义替换实现。

我们强烈建议你不要改变默认 Magento 组件和小工具的源代码。所有的定制必须在自定义模块或主题中实现。

添加一个自定义JS组件

添加一个自定义的 JS 组件(模块) , 参考以下步骤:

  1. 把自定义组件的源文件放在以下位置:
    • 主题目录下 vendorName_ModuleName/web/js
    • 模块目录下 /view/frontend/web/js
  2. 可选择,在对应的模块或者主题下,创建一个 requirejs-config.js 配置文件(如果不存在),配置文件可以放在以下位置:
    • 你的主题 <theme_dir>
    • 主题的主题的模块里 <theme_dir>/<module_dir>
    • 你的模块里(base, frontend, adminhtml) : <module_dir>/view/

替换一个默认的JS组件

要使用现有Magento JS组件的自定义实现。 将自定义组件的源文件放在以下位置之一。

  • 你的主题JS文件。/web/js
  • 你的模块视图JS文件。<module_dir>/view/frontend/web/js

创建一个RequireJS配置文件requirejs-config.js,并指定以下内容。


var config = {
  "map": {
    "*": {
      "<default_component>": "<custom_component>"
    }
  }
};

  • <default_component>: the name of the default component you replace
  • <custom_component>: the name of the custom component

例如,如果你想使用自定义的 navigation-menu.js 脚本而不是默认的菜单部件,你的 requirejs-config.js 应该包含以下内容。


var config = {
  "map": {
    "*": {
      "menu": "js/navigation-menu",
      "mage/backend/menu": "js/navigation-menu"
    }
  }
};

将你的requirejs-config.js文件放在以下目录之一(根据你的自定义脚本的位置,见本程序的第1步)。

  • 你的主题文件。<theme_dir>。

  • 你的模块视图文件。<module_dir>/view/frontend

    这样一来,你的自定义JS组件就会在整个前端区域的所有条目中代替Magento组件使用。

扩展一个默认的 JS 组件

扩展 Magento widget

扩展一个默认的 Ui 组件