App components

Before we take a look at the <my-app> component, let's take a look at what happens when you go to localhost:3000. The index.html file runs. The contents of index.html look something like this:

<html>
<head>
<title>My App</title>
</head>
<body>
<my-app></my-app>
<script src="bundle.js"></script>
</body>
</html>

As you can see, it is trying to render the <my-app> component. But it tries to get the definition of MyApp from the bundle.js file. This bundle.js file, as discussed earlier, is a collection of all the components that are required on the page and will be required by the <my-app> component. This bundle.js file is created with the help of webpack. And the configuration of the bundle.js file can be found in the webpack.config.js file, which looks something like this:

entry: './src/index.js',

The entry file that is chosen is the /src/index.js file. But then again, where does the bundle.js part come from? If you look at the bottom in the webpack.config.js file, you will see something like this:

output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},

Here, we are making sure that everything that is inside the entry file, /src/index.js, gets written to the bundle.js file. You can definitely modify this file if you have experience with webpack. But for the sake of simplicity, we are going to leave it as is.

Let's take a look at the /src/index.js file:

import './styles.scss';

import MyApp from './components/my-app';
customElements.define('my-app', MyApp);

What we are seeing here is that, it is importing a styles.scss file, which can be used to store our global styles, and then it is importing our MyApp class from the /components/my-app folder. And then, it defines the custom element. This is something that we have already looked into in Chapter 1, Web Components Essentials and Specifications.

If we look into the MyApp class, we will find that there is nothing different than what we have already learned in the previous chapters. 

The constructor() method is no different:

constructor() {

// We are not even going to touch this.
super();

// lets create our shadow root
this.shadowObj = this.attachShadow({mode: 'open'});
this.render();
}

The render() method is pretty simple as well:

render() {
this.shadowObj.innerHTML = this.getTemplate();
}

The getStyle() and getTemplate() methods are the same as well; no different from what we have learned previously:

getTemplate() {
return `
<div>
My App
</div>
${this.getStyle()}
`;
}

getStyle() {
return `
<style>
:host {
display: block;
}
</style>
`;
}

With the help of the code here, we can understand how the app component works and how it is the most important Web Component in order to make our single page web app work.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
13.59.231.155