简体   繁体   中英

Web component is not loading the shadowDOM in one react app's but is loading in a fresh CRA app?

I followed a tutorial by Maximillion("Udemy") on web components and Stencil. I had tried to add identical code to my dev env in a "production app" and a brand new "CRA(create react app) project".

The results were that the "production app" only returned naked HTML elements?? With no shadow dom attached?

Now the brand new CRA was able to load and render the web components perfectly.

I am trying to understand why this is happening? I have a suspicion that it may be a web-pack thing but I'm not sure.

To reiterate the point, why isn't the shadow dom being rendered in my production app but it is being rendered in my sample POC app?

This was actually a simple fix, I had followed the Tutorial and documents by adding this--

import { defineCustomElements } from 'web-components/loader/index.js';
defineCustomElements(window)

not to the index.js page as instructed---this is the recommended pattern--

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { defineCustomElements } from 'web-components/loader/index.js';
defineCustomElements(window)

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
  <React.StrictMode>
    <App />
  </React.StrictMode>
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
defineCustomElements(window);
reportWebVitals();

This didn't work for me in my current project, but it worked great for me with a nice clean CRA build project.

What I ended up having to do was move this code---

 import { defineCustomElements } from 'web-components/loader/index.js';
    defineCustomElements(window)

to the top of my react-router file, then it worked perfectly. This may be due to react-router.

// AboutPage/index.js
import { Switch, Route } from 'react-router-dom';
import App from '../compopnents/App';
import { defineCustomElements } from 'web-components/loader/index.js';
defineCustomElements(window)

function AboutPage() {
  return (
    <Switch>
         <Route path="/deals" component={ App } />
    </Switch>
  );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM