lm-web-controls 1.4.2 → 1.4.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
|
@@ -0,0 +1 @@
|
|
|
1
|
+
var n={name:"Azure CDN Premium",detectUrl:function(n){return n.includes("azureedge.net")},generateWebP:function(n,t){void 0===t&&(t={});var e=n.includes("?")?"&":"?",a=new URLSearchParams;return a.append("format","webp"),t.quality&&a.append("quality",t.quality.toString()),t.width&&a.append("width",t.width.toString()),"".concat(n).concat(e).concat(a.toString())},generateResponsive:function(n,t,e){void 0===e&&(e={});var a=n.includes("?")?"&":"?",r=new URLSearchParams;return r.append("width",t.toString()),e.quality&&r.append("quality",e.quality.toString()),"".concat(n).concat(a).concat(r.toString())}},t={name:"Azure Blob Storage",detectUrl:function(n){return n.includes("blob.core.windows.net")},generateWebP:function(n,t){var e=n.split("?")[0],a=e.replace(/\.(png|jpg|jpeg)$/i,".webp");return a!==e?a:n},generateResponsive:function(n,t,e){return n}},e={name:"Cloudinary",detectUrl:function(n){return n.includes("cloudinary.com")},generateWebP:function(n,t){void 0===t&&(t={});var e=t.quality||"auto",a=t.width?",w_".concat(t.width):"";return n.replace("/upload/","/upload/f_webp,q_".concat(e).concat(a,"/"))},generateResponsive:function(n,t,e){void 0===e&&(e={});var a=e.quality||"auto";return n.replace("/upload/","/upload/w_".concat(t,",q_").concat(a,"/"))}},a={name:"ImageKit",detectUrl:function(n){return n.includes("imagekit.io")},generateWebP:function(n,t){void 0===t&&(t={});var e=n.includes("?")?"&":"?",a=t.quality||80,r=t.width?",w-".concat(t.width):"";return"".concat(n).concat(e,"tr=f-webp,q-").concat(a).concat(r)},generateResponsive:function(n,t,e){void 0===e&&(e={});var a=n.includes("?")?"&":"?",r=e.quality||80;return"".concat(n).concat(a,"tr=w-").concat(t,",q-").concat(r)}},r={name:"Vercel Image Optimization",detectUrl:function(n){return!1},generateWebP:function(n,t){void 0===t&&(t={});var e=new URLSearchParams;return e.append("url",encodeURIComponent(n)),e.append("w",(t.width||1920).toString()),e.append("q",(t.quality||75).toString()),e.append("f","webp"),"/_next/image?".concat(e.toString())},generateResponsive:function(n,t,e){void 0===e&&(e={});var a=new URLSearchParams;return a.append("url",encodeURIComponent(n)),a.append("w",t.toString()),a.append("q",(e.quality||75).toString()),"/_next/image?".concat(a.toString())}},i={name:"Generic",detectUrl:function(){return!0},generateWebP:function(n,t){void 0===t&&(t={});var e=n.includes("?")?"&":"?",a=new URLSearchParams;return a.append("format","webp"),t.quality&&a.append("quality",t.quality.toString()),t.width&&a.append("w",t.width.toString()),"".concat(n).concat(e).concat(a.toString())},generateResponsive:function(n,t,e){void 0===e&&(e={});var a=n.includes("?")?"&":"?",r=new URLSearchParams;return r.append("w",t.toString()),e.quality&&r.append("q",e.quality.toString()),"".concat(n).concat(a).concat(r.toString())}},o=[n,t,e,a,r,i],c=function(n){return o.find(function(t){return t.detectUrl(n)})||i},u=function(n){var t,e=(null===(t=n.split(".").pop())||void 0===t?void 0:t.toLowerCase())||"";return["webp","avif"].includes(e)};export{t as azureBlobConfig,n as azureCdnConfig,e as cloudinaryConfig,i as genericConfig,c as getImageServiceConfig,o as imageServiceConfigs,a as imagekitConfig,u as isOptimizedFormat,r as vercelConfig};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import{__assign as t}from"../../_virtual/_tslib.js";import e,{useState as o,useRef as i,useEffect as n}from"react";function r(r){var l=r.src,a=r.alt,c=r.className,s=void 0===c?"":c,d=r.
|
|
2
|
+
import{__assign as t}from"../../_virtual/_tslib.js";import e,{useState as o,useRef as i,useEffect as n}from"react";function r(r){var l=r.src,a=r.alt,c=r.className,s=void 0===c?"":c,d=r.sizes,f=r.priority,u=void 0!==f&&f,p=r.quality,m=void 0===p?75:p,v=r.placeholder,b=void 0===v?"empty":v,h=r.blurDataURL,g=r.onLoad,y=r.onError,x=r.fill,w=void 0!==x&&x,j=r.style,E=o(!1),z=E[0],k=E[1],C=o(!1),F=C[0],I=C[1],S=o(u),L=S[0],q=S[1],N=i(null),P=i(null);n(function(){if(!u&&!L){var t=new IntersectionObserver(function(e){e.forEach(function(e){e.isIntersecting&&(q(!0),t.disconnect())})},{rootMargin:"50px 0px",threshold:.1});return P.current&&t.observe(P.current),function(){return t.disconnect()}}},[u,L]);var _={ref:N,alt:a,onLoad:function(){k(!0),null==g||g()},onError:function(){I(!0),null==y||y()},loading:u?"eager":"lazy",sizes:d,style:t({objectFit:"cover",objectPosition:"center"},j)},D=t({position:w?"absolute":"relative",display:"block",overflow:"hidden"},w?{top:0,left:0,bottom:0,right:0}:{}),M=t({position:w?"absolute":"static",top:w?0:void 0,left:w?0:void 0,bottom:w?0:void 0,right:w?0:void 0,boxSizing:"border-box",padding:0,border:"none",margin:"auto",display:"block",width:"100%",height:w?"100%":"auto",maxWidth:"100%",objectFit:"cover",objectPosition:"center",transition:"opacity 0.3s ease",opacity:z?1:0},_.style);return e.createElement("div",{ref:P,className:s,style:D},!z&&!F&&e.createElement("div",{style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",backgroundColor:"#f3f4f6",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"12px",color:"#9ca3af"}},"blur"===b&&h?e.createElement("img",{src:h,alt:"",style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",objectFit:"cover",filter:"blur(10px)",transform:"scale(1.1)"}}):null),F&&e.createElement("div",{style:{position:"absolute",top:0,left:0,width:"100%",height:"100%",backgroundColor:"#fef2f2",display:"flex",alignItems:"center",justifyContent:"center",fontSize:"12px",color:"#dc2626"}},"Failed to load image"),L&&e.createElement("img",t({},_,{src:l,srcSet:d?function(){if(d){return[640,750,828,1080,1200,1920,2048].map(function(t){var e=l.includes("?")?"&":"?";return"".concat(l).concat(e,"w=").concat(t,"&q=").concat(m," ").concat(t,"w")}).join(", ")}}():void 0,style:M})))}var l=function(t){if("undefined"!=typeof window){var e=document.createElement("link");e.rel="preload",e.as="image",e.href=t,document.head.appendChild(e)}};export{r as OptimizedImage,l as preloadImage};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import e from"react";import{OptimizedImage as t}from"../optimizedImage/index.js";function a(a){var
|
|
2
|
+
import e from"react";import{OptimizedImage as t}from"../optimizedImage/index.js";function a(a){var l=a.relatedPosts,r=a.title,s=a.nestedUrl,c=a.category;return l.length?e.createElement("div",{className:"related-posts-main-container"},e.createElement("h2",{className:"related-posts-title"},r||"Related Posts"),e.createElement("div",{className:"related-posts"},l.map(function(a,l){return e.createElement("a",{key:l,className:"related-post-item",href:"".concat(s?"/".concat(s):"","/post").concat(c?"/".concat(a.categoryInfo.slug):"","/").concat(a.slug)},e.createElement(t,{src:a.featuredImage,alt:a.title,className:"related-post-item-image"}),e.createElement("h3",{className:"related-post-item-title"},a.title))}))):null}export{a as RelatedPosts};
|
package/package.json
CHANGED
package/IMAGE_OPTIMIZATION.md
DELETED
|
@@ -1,236 +0,0 @@
|
|
|
1
|
-
# Image Optimization Guide for lm-web-controls
|
|
2
|
-
|
|
3
|
-
## Overview
|
|
4
|
-
|
|
5
|
-
The `lm-web-controls` package now includes comprehensive image optimization through the `OptimizedImage` component. This guide explains how images are optimized across all blog-related controls and how to configure image optimization for your use case.
|
|
6
|
-
|
|
7
|
-
## What's Been Optimized
|
|
8
|
-
|
|
9
|
-
All blog-related components now use the `OptimizedImage` component instead of standard `<img>` tags:
|
|
10
|
-
|
|
11
|
-
- **FeaturedBlog**: Main featured blog image
|
|
12
|
-
- **Post**: Featured image in post details
|
|
13
|
-
- **BlogList**: All blog thumbnails in both grid and list views
|
|
14
|
-
- **RelatedPosts**: Thumbnail images for related posts
|
|
15
|
-
|
|
16
|
-
## Key Features
|
|
17
|
-
|
|
18
|
-
### 1. Lazy Loading
|
|
19
|
-
- Images load only when they enter the viewport
|
|
20
|
-
- Reduces initial page load time
|
|
21
|
-
- Can be disabled for above-the-fold images using `priority={true}`
|
|
22
|
-
|
|
23
|
-
### 2. Responsive Images
|
|
24
|
-
- Automatically serves different image sizes based on screen size
|
|
25
|
-
- Reduces bandwidth usage on mobile devices
|
|
26
|
-
- Configurable breakpoints for different device types
|
|
27
|
-
|
|
28
|
-
### 3. Modern Format Support
|
|
29
|
-
- Supports WebP and AVIF formats for better compression
|
|
30
|
-
- Automatically falls back to JPEG/PNG for older browsers
|
|
31
|
-
- Uses HTML5 `<picture>` element for optimal format selection
|
|
32
|
-
|
|
33
|
-
### 4. Performance Features
|
|
34
|
-
- Intersection Observer for efficient lazy loading
|
|
35
|
-
- Image preloading for critical above-the-fold images
|
|
36
|
-
- Loading states and error handling
|
|
37
|
-
- Optional blur placeholder while loading
|
|
38
|
-
|
|
39
|
-
## Configuration Options
|
|
40
|
-
|
|
41
|
-
### Basic Usage
|
|
42
|
-
```tsx
|
|
43
|
-
import { OptimizedImage } from 'lm-web-controls';
|
|
44
|
-
|
|
45
|
-
<OptimizedImage
|
|
46
|
-
src="https://example.com/image.jpg"
|
|
47
|
-
alt="Description"
|
|
48
|
-
className="my-image-class"
|
|
49
|
-
/>
|
|
50
|
-
```
|
|
51
|
-
|
|
52
|
-
### Advanced Configuration
|
|
53
|
-
```tsx
|
|
54
|
-
<OptimizedImage
|
|
55
|
-
src="https://example.com/image.jpg"
|
|
56
|
-
alt="Description"
|
|
57
|
-
className="my-image-class"
|
|
58
|
-
priority={true} // Load immediately, no lazy loading
|
|
59
|
-
quality={90} // Image quality (1-100)
|
|
60
|
-
responsive={{
|
|
61
|
-
small: 640, // Mobile: up to 640px
|
|
62
|
-
medium: 768, // Tablet: up to 768px
|
|
63
|
-
large: 1024, // Desktop: up to 1024px
|
|
64
|
-
xlarge: 1920 // Large desktop: 1024px+
|
|
65
|
-
}}
|
|
66
|
-
sizes="(max-width: 768px) 100vw, 50vw"
|
|
67
|
-
formats={["webp", "avif", "jpg"]}
|
|
68
|
-
placeholder="blur"
|
|
69
|
-
blurDataURL="data:image/jpeg;base64,..."
|
|
70
|
-
/>
|
|
71
|
-
```
|
|
72
|
-
|
|
73
|
-
## Integration with Image Services
|
|
74
|
-
|
|
75
|
-
The `OptimizedImage` component is designed to work with image optimization services. You need to modify the `generateImageUrl` function in the component to match your image service:
|
|
76
|
-
|
|
77
|
-
### Cloudinary Example
|
|
78
|
-
```tsx
|
|
79
|
-
const generateImageUrl = (src, width, format, quality) => {
|
|
80
|
-
return `https://res.cloudinary.com/your-cloud/image/fetch/w_${width},f_${format},q_${quality}/${encodeURIComponent(src)}`;
|
|
81
|
-
};
|
|
82
|
-
```
|
|
83
|
-
|
|
84
|
-
### ImageKit Example
|
|
85
|
-
```tsx
|
|
86
|
-
const generateImageUrl = (src, width, format, quality) => {
|
|
87
|
-
return `https://ik.imagekit.io/your-id/tr:w-${width},f-${format},q-${quality}/${src}`;
|
|
88
|
-
};
|
|
89
|
-
```
|
|
90
|
-
|
|
91
|
-
### Custom Service Example
|
|
92
|
-
```tsx
|
|
93
|
-
const generateImageUrl = (src, width, format, quality) => {
|
|
94
|
-
const params = new URLSearchParams();
|
|
95
|
-
if (width) params.append('w', width.toString());
|
|
96
|
-
if (format) params.append('f', format);
|
|
97
|
-
params.append('q', quality.toString());
|
|
98
|
-
return `${src}?${params.toString()}`;
|
|
99
|
-
};
|
|
100
|
-
```
|
|
101
|
-
|
|
102
|
-
## Component-Specific Optimizations
|
|
103
|
-
|
|
104
|
-
### FeaturedBlog
|
|
105
|
-
- Uses `priority={true}` for immediate loading (above-the-fold)
|
|
106
|
-
- Responsive sizes: `(max-width: 768px) 100vw, 50vw`
|
|
107
|
-
- Supports large image sizes up to 1920px
|
|
108
|
-
|
|
109
|
-
### Post
|
|
110
|
-
- Uses `priority={true}` for immediate loading
|
|
111
|
-
- Full-width responsive: `100vw`
|
|
112
|
-
- Optimized for hero image display
|
|
113
|
-
|
|
114
|
-
### BlogList
|
|
115
|
-
- Uses `lazy={true}` for performance
|
|
116
|
-
- Different sizes for grid vs list view
|
|
117
|
-
- Smaller responsive breakpoints for thumbnails
|
|
118
|
-
|
|
119
|
-
### RelatedPosts
|
|
120
|
-
- Uses `lazy={true}` with smallest image sizes
|
|
121
|
-
- Fixed size: `200px` for consistent layout
|
|
122
|
-
- Optimized for small thumbnail display
|
|
123
|
-
|
|
124
|
-
## Performance Benefits
|
|
125
|
-
|
|
126
|
-
### Before Optimization
|
|
127
|
-
- All images loaded immediately
|
|
128
|
-
- Single image size for all devices
|
|
129
|
-
- No format optimization
|
|
130
|
-
- Large bandwidth usage
|
|
131
|
-
|
|
132
|
-
### After Optimization
|
|
133
|
-
- **60-80% faster initial page load** with lazy loading
|
|
134
|
-
- **30-50% bandwidth reduction** with responsive images
|
|
135
|
-
- **20-40% smaller file sizes** with WebP/AVIF formats
|
|
136
|
-
- **Better Core Web Vitals scores**
|
|
137
|
-
|
|
138
|
-
## Best Practices
|
|
139
|
-
|
|
140
|
-
### 1. Use Priority Loading Wisely
|
|
141
|
-
```tsx
|
|
142
|
-
// Good: Above-the-fold images
|
|
143
|
-
<OptimizedImage priority={true} src="hero-image.jpg" />
|
|
144
|
-
|
|
145
|
-
// Good: Below-the-fold images
|
|
146
|
-
<OptimizedImage lazy={true} src="thumbnail.jpg" />
|
|
147
|
-
```
|
|
148
|
-
|
|
149
|
-
### 2. Configure Appropriate Sizes
|
|
150
|
-
```tsx
|
|
151
|
-
// For hero images
|
|
152
|
-
sizes="100vw"
|
|
153
|
-
|
|
154
|
-
// For thumbnails in grid
|
|
155
|
-
sizes="(max-width: 640px) 100vw, (max-width: 1024px) 50vw, 33vw"
|
|
156
|
-
|
|
157
|
-
// For sidebar images
|
|
158
|
-
sizes="300px"
|
|
159
|
-
```
|
|
160
|
-
|
|
161
|
-
### 3. Set Quality Based on Use Case
|
|
162
|
-
```tsx
|
|
163
|
-
// High quality for hero images
|
|
164
|
-
quality={90}
|
|
165
|
-
|
|
166
|
-
// Standard quality for thumbnails
|
|
167
|
-
quality={75}
|
|
168
|
-
|
|
169
|
-
// Lower quality for background images
|
|
170
|
-
quality={60}
|
|
171
|
-
```
|
|
172
|
-
|
|
173
|
-
## SEO Benefits
|
|
174
|
-
|
|
175
|
-
1. **Improved Page Speed**: Faster loading times improve search rankings
|
|
176
|
-
2. **Better Core Web Vitals**: Optimized LCP (Largest Contentful Paint)
|
|
177
|
-
3. **Reduced Bounce Rate**: Faster pages keep users engaged
|
|
178
|
-
4. **Mobile Optimization**: Responsive images improve mobile experience
|
|
179
|
-
|
|
180
|
-
## Browser Support
|
|
181
|
-
|
|
182
|
-
- **Modern Browsers**: Full WebP/AVIF support with responsive images
|
|
183
|
-
- **Legacy Browsers**: Automatic fallback to JPEG/PNG
|
|
184
|
-
- **All Browsers**: Lazy loading support with intersection observer
|
|
185
|
-
|
|
186
|
-
## Migration Guide
|
|
187
|
-
|
|
188
|
-
If you're upgrading from a previous version:
|
|
189
|
-
|
|
190
|
-
1. **No Breaking Changes**: All existing props continue to work
|
|
191
|
-
2. **Automatic Optimization**: Images are automatically optimized
|
|
192
|
-
3. **Optional Configuration**: Advanced features are opt-in
|
|
193
|
-
4. **Backward Compatible**: Standard `img` behavior if needed
|
|
194
|
-
|
|
195
|
-
## Monitoring and Testing
|
|
196
|
-
|
|
197
|
-
### Performance Testing
|
|
198
|
-
- Use browser DevTools Network tab to verify image loading
|
|
199
|
-
- Check Core Web Vitals in PageSpeed Insights
|
|
200
|
-
- Monitor Cumulative Layout Shift (CLS) scores
|
|
201
|
-
|
|
202
|
-
### Visual Testing
|
|
203
|
-
- Verify images load correctly across different devices
|
|
204
|
-
- Test lazy loading behavior
|
|
205
|
-
- Ensure fallbacks work in older browsers
|
|
206
|
-
|
|
207
|
-
## Common Issues and Solutions
|
|
208
|
-
|
|
209
|
-
### Issue: Images not loading
|
|
210
|
-
**Solution**: Check image service URL generation and CORS settings
|
|
211
|
-
|
|
212
|
-
### Issue: Layout shift during loading
|
|
213
|
-
**Solution**: Always specify width/height or aspect-ratio
|
|
214
|
-
|
|
215
|
-
### Issue: Images too small on high-DPI displays
|
|
216
|
-
**Solution**: Increase responsive breakpoint values
|
|
217
|
-
|
|
218
|
-
### Issue: Slow loading on mobile
|
|
219
|
-
**Solution**: Reduce mobile image sizes in responsive config
|
|
220
|
-
|
|
221
|
-
## Future Enhancements
|
|
222
|
-
|
|
223
|
-
Planned improvements for future versions:
|
|
224
|
-
- Automatic aspect ratio detection
|
|
225
|
-
- Smart cropping based on content
|
|
226
|
-
- Advanced placeholder generation
|
|
227
|
-
- Progressive image loading
|
|
228
|
-
- Integration with more image services
|
|
229
|
-
|
|
230
|
-
## Support
|
|
231
|
-
|
|
232
|
-
For issues or questions about image optimization:
|
|
233
|
-
1. Check this documentation first
|
|
234
|
-
2. Review the component source code
|
|
235
|
-
3. Test with different image services
|
|
236
|
-
4. Open an issue with detailed reproduction steps
|
package/readme.md
DELETED
|
@@ -1,222 +0,0 @@
|
|
|
1
|
-
# How to create a Custom NPM Module with React Components?
|
|
2
|
-
|
|
3
|
-
This repo is aimed to describe the process of creating a custom NPM package/module with React.JS components. It will guide you through the steps of setting up your development environment, writing and exporting your components, and publishing your package to the NPM registry[Optional]. Additionally, it will provide tips and best practices for maintaining and updating your package.
|
|
4
|
-
|
|
5
|
-
## Installation
|
|
6
|
-
|
|
7
|
-
**Step 1:** Make a directory and initialize npm.
|
|
8
|
-
|
|
9
|
-
```bash
|
|
10
|
-
mkdir custom-npm-package
|
|
11
|
-
npm init
|
|
12
|
-
```
|
|
13
|
-
|
|
14
|
-
Alternatively, you can use the following command to quickly generate a minimal boilerplate:
|
|
15
|
-
|
|
16
|
-
```bash
|
|
17
|
-
npm init -y
|
|
18
|
-
```
|
|
19
|
-
|
|
20
|
-
Add the necessary fields. After the successfull walkthrough a package.json will created and looks like below.
|
|
21
|
-
|
|
22
|
-
```bash
|
|
23
|
-
{
|
|
24
|
-
"name": "gittuts",
|
|
25
|
-
"version": "1.0.0",
|
|
26
|
-
"description": "",
|
|
27
|
-
"main": "index.js",
|
|
28
|
-
"scripts": {
|
|
29
|
-
"test": "echo \"Error: no test specified\" && exit 1"
|
|
30
|
-
},
|
|
31
|
-
"author": "",
|
|
32
|
-
"license": "ISC"
|
|
33
|
-
}
|
|
34
|
-
```
|
|
35
|
-
|
|
36
|
-
**Step 2:** Create a src folder in the root add a index.js/index.ts in it also create a component folder and creates some components in it.
|
|
37
|
-
|
|
38
|
-
```bash
|
|
39
|
-
src
|
|
40
|
-
├── components
|
|
41
|
-
│ ├── Component1
|
|
42
|
-
│ │ └── index.tsx
|
|
43
|
-
│ ├── Component2
|
|
44
|
-
│ │ └── index.tsx
|
|
45
|
-
│ └── Component3
|
|
46
|
-
│ └── index.tsx
|
|
47
|
-
└── index.ts
|
|
48
|
-
```
|
|
49
|
-
|
|
50
|
-
**Step 3:** Now, Add react and react-dom as peer-dependencies and dev-dependencies.
|
|
51
|
-
|
|
52
|
-
```bash
|
|
53
|
-
yarn add react react-dom --dev
|
|
54
|
-
|
|
55
|
-
or
|
|
56
|
-
|
|
57
|
-
npm install react react-dom --dev
|
|
58
|
-
```
|
|
59
|
-
|
|
60
|
-
The final package.json may looks like below.
|
|
61
|
-
|
|
62
|
-
```bash
|
|
63
|
-
{
|
|
64
|
-
"name": "custom-npm-package",
|
|
65
|
-
"version": "1.0.0",
|
|
66
|
-
"description": "react custom npm module",
|
|
67
|
-
"main": "index.js",
|
|
68
|
-
"scripts": {
|
|
69
|
-
"test": "echo \"Error: no test specified\" && exit 1",
|
|
70
|
-
"build": "npx babel src --out-file index.js --extensions .ts,.tsx"
|
|
71
|
-
},
|
|
72
|
-
"author": "Anandhu",
|
|
73
|
-
"license": "ISC",
|
|
74
|
-
"peerDependencies": {
|
|
75
|
-
"react": "^18.2.0",
|
|
76
|
-
"react-dom": "^18.2.0"
|
|
77
|
-
},
|
|
78
|
-
"devDependencies": {
|
|
79
|
-
"@types/react": "^18.0.34",
|
|
80
|
-
"react": "^18.2.0",
|
|
81
|
-
"react-dom": "^18.2.0",
|
|
82
|
-
"typescript": "^5.0.4"
|
|
83
|
-
}
|
|
84
|
-
}
|
|
85
|
-
```
|
|
86
|
-
|
|
87
|
-
Since it is Typescript. I've also installed typescript, typescript react with it.
|
|
88
|
-
|
|
89
|
-
**Step 4:** Its time to bundle the code. Install [rollup.js](https://rollupjs.org/)
|
|
90
|
-
|
|
91
|
-
```bash
|
|
92
|
-
npm install --save react rollup
|
|
93
|
-
```
|
|
94
|
-
You will also need to install the Rollup plugins for Babel, CommonJS, and Node Resolve by running
|
|
95
|
-
|
|
96
|
-
```bash
|
|
97
|
-
npm install --save-dev @rollup/plugin-babel @rollup/plugin-commonjs @rollup/plugin-node-resolve rollup-plugin-terser
|
|
98
|
-
|
|
99
|
-
```
|
|
100
|
-
|
|
101
|
-
**Step 5:** Configure Rollup
|
|
102
|
-
|
|
103
|
-
Create a `rollup.config.mjs` or `rollup.config.js` file in the root of your project. In this file, configure Rollup to bundle your React component by specifying the input file, output format, and plugins to use. Here is an example configuration:
|
|
104
|
-
|
|
105
|
-
```bash
|
|
106
|
-
import babel from 'rollup-plugin-babel';
|
|
107
|
-
import resolve from '@rollup/plugin-node-resolve';
|
|
108
|
-
import external from 'rollup-plugin-peer-deps-external';
|
|
109
|
-
import terser from '@rollup/plugin-terser';
|
|
110
|
-
import typescript from "rollup-plugin-typescript2"; // For Typescript
|
|
111
|
-
|
|
112
|
-
export default [
|
|
113
|
-
{
|
|
114
|
-
input: './src/index.ts',
|
|
115
|
-
output: [
|
|
116
|
-
{
|
|
117
|
-
file: 'dist/index.js',
|
|
118
|
-
format: 'cjs',
|
|
119
|
-
},
|
|
120
|
-
{
|
|
121
|
-
file: 'dist/index.es.js',
|
|
122
|
-
format: 'es',
|
|
123
|
-
exports: 'named',
|
|
124
|
-
}
|
|
125
|
-
],
|
|
126
|
-
plugins: [
|
|
127
|
-
babel({
|
|
128
|
-
exclude: 'node_modules/**',
|
|
129
|
-
presets: ['@babel/preset-react']
|
|
130
|
-
}),
|
|
131
|
-
external({
|
|
132
|
-
includeDependencies: true
|
|
133
|
-
}),
|
|
134
|
-
resolve(),
|
|
135
|
-
terser(),
|
|
136
|
-
typescript({ useTsconfigDeclarationDir: true }),
|
|
137
|
-
]
|
|
138
|
-
}
|
|
139
|
-
];
|
|
140
|
-
|
|
141
|
-
```
|
|
142
|
-
|
|
143
|
-
To our package.json, let's add this as build command so that we won't have to type it repeatedly. Under "scripts" in package.json add the following.
|
|
144
|
-
|
|
145
|
-
```bash
|
|
146
|
-
"scripts": {
|
|
147
|
-
"test": "echo \"Error: no test specified\" && exit 1",
|
|
148
|
-
"build": "npx rollup -c"
|
|
149
|
-
}
|
|
150
|
-
```
|
|
151
|
-
|
|
152
|
-
now we can simply use ```npm run build``` or ```yarn build``` to bundle the code.
|
|
153
|
-
|
|
154
|
-
If it compiled without any error you may see a new folder `dist` generated in the root folder with transpiled Javascript Code.
|
|
155
|
-
|
|
156
|
-

|
|
157
|
-
|
|
158
|
-
_image: bundled output_
|
|
159
|
-
|
|
160
|
-
Note: that if you're using a build tool like Webpack, you may not need to use npx babel at all. Instead, you can use a TypeScript loader like ts-loader or awesome-typescript-loader that will transpile and transform your TypeScript files as part of the build process.
|
|
161
|
-
|
|
162
|
-
**Step 6:** Lets pack it so we can use/test it in other projects. Run the following command from the root folder.
|
|
163
|
-
|
|
164
|
-
```bash
|
|
165
|
-
npm pack
|
|
166
|
-
```
|
|
167
|
-
This will generate a .tgz file that we can use to install the package locally in other projects.
|
|
168
|
-
|
|
169
|
-
Alternatively, you can link the package for testing purpose(Recommended).
|
|
170
|
-
|
|
171
|
-
Using `npm link` in your package's root directory, create a global symlink of your package. A shortcut that directs your system to another directory or file is known as a "symlink," short for symbolic link.
|
|
172
|
-
|
|
173
|
-
Now, create an another application and tell the application to use the global symlink with `npm link your-package-name`. This way, we could save a lot of time.
|
|
174
|
-
|
|
175
|
-
**Step 7:** Navigate to your other project's directory and install your package using npm install <path to tarball file>. For example:
|
|
176
|
-
|
|
177
|
-
```bash
|
|
178
|
-
npm i 'path_to_the_packed_file'
|
|
179
|
-
```
|
|
180
|
-
|
|
181
|
-
**Step 8:** In your host project's code you can import and use your component as follows:
|
|
182
|
-
|
|
183
|
-
```bash
|
|
184
|
-
import logo from "./logo.svg";
|
|
185
|
-
import "./App.css";
|
|
186
|
-
import TextInput from "my_npm_package"; // Importing from the package
|
|
187
|
-
import { useState } from "react";
|
|
188
|
-
|
|
189
|
-
function App() {
|
|
190
|
-
const [value, setValue] = useState('');
|
|
191
|
-
console.log(value)
|
|
192
|
-
|
|
193
|
-
function handleChange(e) {
|
|
194
|
-
setValue(e.target.value);
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
return (
|
|
198
|
-
<div className="App">
|
|
199
|
-
<header className="App-header">
|
|
200
|
-
<img src={logo} className="App-logo" alt="logo" />
|
|
201
|
-
<p>Custom npm module.</p>
|
|
202
|
-
<TextInput label="Name" value={value} onChange={handleChange} />
|
|
203
|
-
</header>
|
|
204
|
-
</div>
|
|
205
|
-
);
|
|
206
|
-
}
|
|
207
|
-
|
|
208
|
-
export default App;
|
|
209
|
-
|
|
210
|
-
```
|
|
211
|
-
|
|
212
|
-
Additionally we can use packages like [storybook.js](https://storybook.js.org/) to build UI components and pages in isolation and by doing so we could see the changes that happens to our components without the need of installing it in a host application. You could find the documention for implementing story book [here](https://storybook.js.org/docs/react/get-started/install/).
|
|
213
|
-
|
|
214
|
-
**Step 9:** Publishing our package to NPM Registry
|
|
215
|
-
|
|
216
|
-
To publish a package to the npm registry, we need to follow these steps:
|
|
217
|
-
|
|
218
|
-
- Create an npm account on [npmjs.com](https://www.npmjs.com/signup).
|
|
219
|
-
- Sign in to npm from your terminal using the ```npm login``` command.
|
|
220
|
-
- Prepare your package for publishing.
|
|
221
|
-
- Publish the package from the terminal using the ```npm publish``` command.
|
|
222
|
-
- React 18 Version 1.3.2.
|