Build standalone React component to delivery on CDN using umijs

80 Views Asked by At

After building my React application and MyModule I create an html file for test :

<!-- MAIN.html -->
<body>
    <div id="root"></div>
    <script src="http://localhost/cdn/js/MyModule.js.js"></script>
    <script>
        MyModule.mount()
    </script>
</body>

Note: When mounting the component in the admin interface is works fine. But there is No Style loaded in the basic html test.

Result

enter image description here

How to load only my custom css and a necessary antd style without overriding the body css of the MAIN.html file ?

I noticed that MyModule.js.604c4d96.css have been generated with hash.

Expected

I am trying to make React module to delivery as on js file. In order to achieve this I have create three files MyComponent.tsx, MyComponent.less, MyModule.tsx then add an entry in config.ts.

// config.ts
//...
chainWebpack(config) {
  config.entry('MyModule.js').add(path.join(__dirname, '/../src/cdn/js/MyModule.tsx'));
  config.output.filename((chunkData) =>
    chunkData.chunk.name === 'umi' ? '[name].[contenthash:8].js' : 'cdn/js/[name]');
}
//...
// MyModule.tsx
import MyComponent from '@/components/MyComponent';
import { render } from 'react-dom';

const MyModule = {
  mount(element: string = '#root') {
    const container = window.document.querySelector(element);
    if (!container) {
      throw new Error(`Can't found element ('${element}') in your document`);
    }
    render(<MyComponent />, container);
  },
};

window.MyModule = MyModule;
// MyComponent.tsx
import 'antd/dist/antd.css';
import { Form, InputNumber, Select } from 'antd';
import styles from './MyComponent.less';

const MyComponent: React.FC = () => {
  return (
    <Form className={styles.MyStyle}>
      <InputNumber />
      <Select />
    </Form>
  );
};

export default MyComponent;
/* MyComponent.less */
.MyStyle {
  background-color: #f00;
}

Thank you in advance !

0

There are 0 best solutions below