RE: Using SPA Frameworks to build DXP Fragments (Sections, Components)

Michael Freeman, modified 5 Years ago. Junior Member Posts: 37 Join Date: 7/2/12 Recent Posts
Is it possible to use a SPA framework (e.g., React, Vue) to build one of the new DXP fragments? (presumably using the CLI)If so are there any pointers/samples available?
thumbnail
Christoph Rabel, modified 5 Years ago. Liferay Legend Posts: 1555 Join Date: 9/24/09 Recent Posts
In general yes. I wrote a blog post how we write our applications nowadays and the same could be done with fragments. Of course, this is just one way, with pros and cons.
https://liferay.dev/blogs/-/blogs/developing-javascript-frontends-with-webpack
Basically:
1) We add javascript to the page that registers a webcomponent (note: this only works in IE with the proper polyfills). Even with polyfills, that javascript is pretty small.
class HelloWorld extends HTMLElement {
  connectedCallback() {
  import( './components/Hello/hello.js').then(module => {
     module.default(this);
   }).catch(error => console.error('An error occurred while loading the component `HelloWorld`', error));
  }
}
register('hello-world', HelloWorld);

2) The moment a tag <hello-world></hello-world> is added to the page, connectedCallback is executed and hello.js is loaded dynamically. It could be a react app, then it would load also react and all dependencies.
So, you could simply add the javascript globally and put the tag in a fragment and it would work. The overhead of the "init" javascript is rather small, especially since everything else is lazy loaded.