Web Components is a web standard which can be run in different browsers directly. However, it is not easy to create a web component by using native javascript. Although we have polymer, we would like to build web components with react much more. React is so awesome that we use it anywhere now, even in embedded devices. After read the react official blog, I found it not easy to create a web component with react. So I want to provide a way to help developers to build more conveniently.
Nautil is a js framework written by me, it is built on react, so is completely compatible with react components. We will use nautil-cli which is the CLI tool of nautil to create a react web component.
Now, let's do it!
Generate
It is very easy to generate an empty project, by using:
mkdir nautil-app && cd nautil-app
npx nautil-cli init
After a while, the project files are generated by nautil-cli. The directory structure is easy to understand.
Because we are going to write a web component only, so let us delete the no use files and modify package.json
to keep web component scripts only.
Coding
All are ready! Now let's coding.
Open the src/app/app.jsx
and copy your original react component's code here. Because nautil is compatible with react, so you do not need to worry.
Open the src/web-component/index.js
to change the name of your web component. And change the invoking in index.html
.
Preview
To preview the effect, run the following CLI command:
npm run dev:webc
And open your browser to view.
Build
To bundle, run:
npm run build:webc
And your will get the bundle files in dist/web-component
directory.
End
This is how to create a web component with react by using Nautil-CLI tool. Isn't it easy?
Maybe you want to know why, or be interested in the implement of nautil. Then you can look into the source code on github with the preious given link. If you want to know more, join me on github.
Top comments (0)