JavaScript
JavaScript
The Cosmos Web Components first need to be registered in the browser's custom elements registry to become available.
Cosmos exports helpers to make the task as easy as possible. Each component comes with a method that will perform the registration for itself, as well as all its dependencies.
import {
defineCustomElementCosmosButton,
defineCustomElementCosmosText,
} from "@cosmos/web";
// Defining the Cosmos components will register them
// and their dependencies in the global custom element registry
defineCustomElementCosmosButton();
defineCustomElementCosmosText();Using webpack or any other bundler creates an application script that includes the implementation of Cosmos web components.
💡 Pro Tip
The library is optimized for tree-shaking – which allows only code to be bundled in your application that is actually required to render components from Cosmos.
A webpack configuration could look like this.
const path = require('path');
module.exports = {
entry: './src/main.js',
mode: 'production',
output: {
filename: 'main.js',
path: path.resolve(__dirname, './dist/'),
}
};The custom elements can now be used and rendered to your HTML document.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title>Cosmos Web</title>
</head>
<body>
<cosmos-text>Cosmos Text</cosmos-text>
<cosmos-button>Cosmos Button</cosmos-button>
<script src="main.js"></script>
</body>
</html>