Skip to content

premail/mjml-custom-component

Repository files navigation

Compiling an MJML custom component. This repo builds on MJML's custom component boilerplate by demonstrating how to use the component once you've compiled it.


Brought to you by Premail.


Requirements

  • Node 12.x+, npm 6.14.12+
  • Gulp 4.0.2+
  • Tested with MJML 4.12.0

The boilerplate repo uses a specific workflow with Babel, and older versions of MJML, but your own build's workflow doesn't need to match.

To that end: The example in this repo (Stage 2) uses the modern pipeline() version of Gulp workflows (unlike the boilerplate example), but does not use Babel.

Stage 1: Compile the custom component

  1. In a separate folder, clone https://github.com/mjmlio/mjml-component-boilerplate
  2. Run npm install in that folder.
  3. Create a new component, or use the existing examples.
  4. Run gulp build.
  5. Note the compiled component file in ./lib.

Stage 2: Use the compiled component

  1. Clone this repo.
  2. Run npm install in this folder.
  3. Copy the compiled component from Stage 1 into ./components.
  4. Require and register the component in the gulp file:
// Register custom MJML components
const { registerComponent } = require('mjml-core')
const MjBasicComponent = require('./components/MjBasicComponent.js').default
registerComponent(MjBasicComponent)
  1. Require and register the validation (this seems to be necessary in addition to defining it in the component file itself):
const { registerDependencies } = require('mjml-validator')
registerDependencies({
  // Tell the validator which tags are allowed as our component's parent
  'mj-hero': ['mj-basic-component'],
  'mj-column': ['mj-basic-component'],
  // Tell the validator which tags are allowed as our component's children
  'mj-basic-component': []
})
  1. Edit ./src/index.mjml to include the custom component.
  2. Run gulp to create the compiled HTML in ./dist.
  3. Using this as an example, create and use your own custom MJML components!
  4. If you want to contribute your custom component back, add an .mjmlconfig file to your project (here's an example) and publish it to npm! Then suggest the MJML folks add it to their list of community components.

License

GNU Affero General Public License v3.0 or later. For the legal details of the AGPL, see the complete LICENSE.