Welcome to 16892 Developer Community-Open, Learning,Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

My company has a few different websites, mostly with a react front end but a couple without.

We want to build a cookie bar that can just be imported and used anywhere...basically it should be framework independent and ideally an npm package.

I'm not entirely sure if this is possible but I had the idea to construct the cookie bar package with react...it would be super simple, just a few components with jsx and styling and once that is all done, use webpack to compile it all into vanilla javascript that is independent of react and can just be inserted on any site with any or no framework.

All of the html of the cookie bar (that would have originally been written as react components / jsx but then compiled into vanilla JS with webpack) which will then be injected into the html of the website where the script is included.

Is this possible?

All I can find online is people making react components as npm packages but this is not exactly what I am looking to achieve.

Thanks in advance!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
3.1k views
Welcome To Ask or Share your Answers For Others

1 Answer

This is absolutely possible.

If the target page doesn't have React in it at all, you may want to bundle it as a tiny app and mount it as in the answers here. If it does have React, you can probably find away to use the existing React by putting it on window in the other code (import React from 'react'; window.React = React.

For bundling a single component or a few components, you may have better luck with Rollup than Webpack (they have different use-cases; both are bundlers, but Rollup has some niceties for bundling libraries specifically). This example may be useful (it also includes Sass, Storybook, and some other extras that you might or might not need). This would give you more flexibility and possibly smaller bundles, but would mean you'd still need a React app to actually import and use the components, as above.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to 16892 Developer Community-Open, Learning and Share
...