Creating Scripts and Components
In MageObsidian Components, themes can include custom JavaScript logic and Vue components to extend their functionality. These files should be placed under the theme directory:
Specifically:
- Custom JavaScript:
- Vue Components:
This process follows the same workflow explained for modules, ensuring consistency and ease of use.
Workflow
1. JavaScript in web/js
The web/js
directory is intended for general-purpose JavaScript files that handle custom logic or utility functions. Files placed here are automatically processed by Vite and included in the frontend as needed.
Example:
1 2 3 4 5 6 |
|
Usage in .phtml
:
2. Vue Components in web/components
The web/components
directory is designed for Vue Single File Components (SFC). Each component should follow Vue’s structure, leveraging the Composition API for better modularity and flexibility.
Example:
Usage in .phtml
:
Guidelines and Recommendations
-
Consistent Workflow
The workflow for including scripts in themes is the same as for modules:- Use
web/js
for general-purpose JavaScript. - Use
web/components
for Vue components.
- Use
-
File Location
Ensure that your files are placed under the correct paths in the theme directory:- JavaScript:
app/design/frontend/Vendor/Theme/web/js
- Components:
app/design/frontend/Vendor/Theme/web/components
- JavaScript:
-
File Naming Conventions
- Use kebab-case or camelCase for file names in
web/js
. - Use PascalCase for Vue component files in
web/components
.
- Use kebab-case or camelCase for file names in
-
Dynamic Imports
Dynamic imports can be used for JavaScript files to optimize performance: -
Vite Processing
Bothweb/js
andweb/components
are processed by Vite:- Files are optimized and bundled.
- Tree-shaking ensures only necessary code is included.
Example Workflow
Here’s a practical example of including both a custom script and a Vue component in a theme:
-
Create a Custom Script:
File:app/design/frontend/Vendor/Theme/web/js/theme-logic.js
-
Create a Vue Component:
File:app/design/frontend/Vendor/Theme/web/components/CartSummary.vue
-
Include in
.phtml
:
Benefits
-
Unified Workflow
Consistent methodology across modules and themes simplifies development and maintenance. -
Modern Tooling
Vite ensures optimized bundling and faster builds, with support for tree-shaking and ES modules. -
Flexibility
Allows custom logic and Vue components to seamlessly integrate into the frontend, enhancing functionality and user experience.
By following these guidelines, you can create a well-organized and efficient theme that leverages MageObsidian Components for maximum performance and scalability.