0
# Offline Plugin
1
2
Offline Plugin is a webpack plugin that provides offline-first capabilities for webpack-based web applications. It automatically generates ServiceWorker and AppCache (as fallback) configurations to enable applications to work reliably without internet connectivity by intelligently caching webpack output assets.
3
4
## Package Information
5
6
- **Package Name**: offline-plugin
7
- **Package Type**: npm
8
- **Language**: JavaScript with TypeScript definitions
9
- **Installation**: `npm install offline-plugin --save-dev`
10
11
## Core Imports
12
13
Plugin (for webpack configuration):
14
```javascript
15
const OfflinePlugin = require('offline-plugin');
16
```
17
18
Runtime (for client-side code):
19
```javascript
20
require('offline-plugin/runtime').install();
21
```
22
23
ES6/TypeScript:
24
```javascript
25
import * as OfflinePluginRuntime from 'offline-plugin/runtime';
26
OfflinePluginRuntime.install();
27
```
28
29
Access default options:
30
```javascript
31
const OfflinePlugin = require('offline-plugin');
32
console.log(OfflinePlugin.defaultOptions); // View default configuration
33
```
34
35
## Basic Usage
36
37
### 1. Add to webpack configuration
38
39
```javascript
40
// webpack.config.js
41
const OfflinePlugin = require('offline-plugin');
42
43
module.exports = {
44
// ... your webpack config
45
plugins: [
46
// ... other plugins
47
// OfflinePlugin should be the last plugin
48
new OfflinePlugin()
49
]
50
};
51
```
52
53
### 2. Initialize in client code
54
55
```javascript
56
// In your main entry file
57
require('offline-plugin/runtime').install();
58
```
59
60
With update handling:
61
```javascript
62
require('offline-plugin/runtime').install({
63
onUpdateReady: () => {
64
console.log('SW Event:', 'onUpdateReady');
65
// Update available, apply it
66
require('offline-plugin/runtime').applyUpdate();
67
},
68
onUpdated: () => {
69
console.log('SW Event:', 'onUpdated');
70
// App updated, reload page
71
window.location.reload();
72
}
73
});
74
```
75
76
## Architecture
77
78
Offline Plugin operates at two levels:
79
80
- **Build-time Integration**: The main `OfflinePlugin` class hooks into webpack's compilation process to analyze assets, generate cache manifests, and create optimized ServiceWorker and AppCache configurations
81
- **Runtime Management**: The runtime API provides client-side functions to install, update, and manage the offline functionality
82
- **Caching Strategy**: Configurable caching policies (cache-first, network-first) with intelligent asset categorization
83
- **Update Mechanism**: Automatic detection and application of cache updates with configurable strategies
84
85
## Capabilities
86
87
### Plugin Configuration
88
89
Complete webpack plugin configuration with extensive options for caching strategies, asset management, and offline behavior customization.
90
91
```javascript { .api }
92
class OfflinePlugin {
93
constructor(options?: PluginOptions);
94
apply(compiler: webpack.Compiler): void;
95
static defaultOptions: PluginOptions;
96
}
97
98
interface PluginOptions {
99
caches?: 'all' | CacheConfiguration;
100
publicPath?: string;
101
updateStrategy?: 'changed' | 'all';
102
responseStrategy?: 'cache-first' | 'network-first';
103
externals?: string[];
104
excludes?: string[];
105
relativePaths?: boolean;
106
version?: string | Function;
107
autoUpdate?: boolean | number;
108
rewrites?: Function | Object;
109
safeToUseOptionalCaches?: boolean;
110
appShell?: string;
111
cacheMaps?: CacheMap[];
112
ServiceWorker?: ServiceWorkerOptions;
113
AppCache?: AppCacheOptions | false;
114
}
115
116
interface CacheConfiguration {
117
main?: string[];
118
additional?: string[];
119
optional?: string[];
120
}
121
122
interface CacheMap {
123
match: string | Function;
124
to?: string | Function;
125
requestTypes?: ('navigate' | 'same-origin' | 'cross-origin')[];
126
}
127
128
interface ServiceWorkerOptions {
129
output?: string;
130
entry?: string;
131
scope?: string;
132
events?: boolean;
133
minify?: boolean;
134
forceInstall?: boolean;
135
updateViaCache?: 'imports' | 'all' | 'none';
136
prefetchRequest?: PrefetchRequestOptions;
137
navigationPreload?: boolean | 'auto';
138
}
139
140
interface AppCacheOptions {
141
directory?: string;
142
NETWORK?: string;
143
FALLBACK?: { [path: string]: string };
144
caches?: string[];
145
events?: boolean;
146
disableInstall?: boolean;
147
includeCrossOrigin?: boolean;
148
}
149
150
interface PrefetchRequestOptions {
151
credentials?: 'same-origin' | 'include' | 'omit';
152
headers?: { [key: string]: string };
153
mode?: 'cors' | 'no-cors' | 'same-origin';
154
cache?: string;
155
}
156
```
157
158
[Plugin Configuration](./plugin-configuration.md)
159
160
### Runtime API
161
162
Client-side API for managing offline functionality, handling updates, and responding to connectivity changes.
163
164
```javascript { .api }
165
function install(options?: InstallOptions): void;
166
function applyUpdate(): void;
167
function update(): void;
168
169
interface InstallOptions {
170
onInstalled?: () => void;
171
onUpdating?: () => void;
172
onUpdateReady?: () => void;
173
onUpdateFailed?: () => void;
174
onUpdated?: () => void;
175
}
176
```
177
178
[Runtime API](./runtime-api.md)
179
180
### Cache Management
181
182
Advanced caching configuration allowing fine-grained control over which assets are cached, how they're organized, and when they're updated.
183
184
Key cache features:
185
- **Asset categorization**: Main, additional, and optional cache sections
186
- **Pattern matching**: Glob patterns and regex support for asset selection
187
- **External resources**: Cache external URLs and third-party assets
188
- **Cache maps**: URL rewriting and request routing rules
189
- **Selective updates**: Choose which assets trigger cache invalidation
190
191
### ServiceWorker Integration
192
193
Automatic ServiceWorker generation with advanced features:
194
- **Navigation preload**: Faster page loads with background requests
195
- **Custom scopes**: Control ServiceWorker registration scope
196
- **Request strategies**: Configurable cache-first or network-first approaches
197
- **Asset prefetching**: Background downloading of updated resources
198
199
### AppCache Fallback
200
201
Legacy AppCache support for older browsers:
202
- **Automatic manifest generation**: Creates AppCache manifest from webpack assets
203
- **Fallback configuration**: Specify offline fallback pages
204
- **Network allowlist**: Control which requests bypass the cache
205
206
## Constants and Special Values
207
208
```javascript { .api }
209
// Special cache keywords (used in cache configuration arrays)
210
const CACHE_KEYWORDS = {
211
REST: ':rest:', // Include all remaining uncategorized assets
212
EXTERNALS: ':externals:' // Include all external URLs
213
};
214
215
// Auto-update default interval
216
const DEFAULT_AUTO_UPDATE_INTERVAL = 3600000; // 1 hour in milliseconds
217
218
// Valid update strategies
219
const UPDATE_STRATEGIES = ['changed', 'all'];
220
221
// Valid response strategies
222
const RESPONSE_STRATEGIES = ['cache-first', 'network-first'];
223
224
// Valid updateViaCache values
225
const UPDATE_VIA_CACHE_OPTIONS = ['imports', 'all', 'none'];
226
```