Overview
In this blog, we will discuss how to add a custom NPM package to the Administration or Storefront. If you are working on a plugin and you need to write a custom Javascript plugin. For this approach, we can add a custom NPM package to our plugin directory.
Adding a npm package to the Administration or the Storefront
Now we add a custom NPM package to the Administration or Storefront. assume you have installed NPM, run npm init -y
it in the plugin directory <plugin root>src/Resources/app/administration/
or the <plugin root>src/Resources/app/storefront/
directory. This commands creates a package.json
file in the respective folder. To add a package to the package.json
file simply run the npm install
command and your desired package will be installed in your node_module folder. In this example, we will be installing missionlog package in our plugin.
Registering a package in the build system
Shopware’s Storefront, as well as Administration, is based on the build system Webpack. Webpack is a source file bundler: In essence, it bundles all the source files into a single bundle.js
to be shipped to a browser. To make Webpack know of the new dependency. We have to register it and give it an alias so that the package can be bundled correctly.
To do this we create a new folder called “build” under either Resources/app/storefront
or Resources/app/administration
. In this build folder, we create a new file with the name webpack.config.js
. We thereby make it possible to extend the Webpack configuration of Shopware.
const { join, resolve } = require('path'); module.exports = () => { return { resolve: { alias: { '@missionlog': resolve( join(__dirname, '..', 'node_modules', 'missionlog') ) } } }; }
Using the dependency
Once we have installed all the dependencies and registered the package in the build system with an alias, we can use the package in our own code.
import Plugin from 'src/plugin-system/plugin.class'; // Import logger import { log } from '@missionlog'; // Initializing the logger log.init({ initializer: 'INFO' }, (level, tag, msg, params) => { console.log(`${level}: [${tag}] `, msg, ...params); }); // The plugin skeleton export default class ExamplePlugin extends Plugin { init() { console.log('init'); // Use logger log.info('initializer', 'example plugin got started', this); } }
Now you can see the log info in the browser console of the custom Javascript plugin in your Storefront.
Multi-Seller Marketplace Plugin
Thanks for reading this blog, I hope it will help you. Happy coding 🙂
Be the first to comment.