简体   繁体   中英

Create npm package with react components that exports to vanilla javascript

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!

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.

Since your project scope is quite small it should not import or embed the whole react library.

I strongly encourage you to check Preactjs ( https://preactjs.com/ ) which lets you write your code in JSX but has a much lighter footprint (3kB atm). Your component will load way faster, especially for mobile users

Then bundling with tools recommended in the other answers (rollup is great) is the way to go

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