File tree Expand file tree Collapse file tree 2 files changed +39
-5
lines changed Expand file tree Collapse file tree 2 files changed +39
-5
lines changed Original file line number Diff line number Diff line change @@ -26,6 +26,15 @@ After:
26
26
27
27
> npm i posthtml posthtml-webp
28
28
29
+ ## Plugin options
30
+ ` replaceExtension ` (boolean)
31
+
32
+ ** Default:** false
33
+
34
+ Replace the extension of the source image with .webp instead of appending .webp to the original filename
35
+
36
+ ** Example** : image.jpg => image.webp (instead of image.jpg.webp)
37
+
29
38
## Usage
30
39
31
40
``` js
@@ -34,7 +43,7 @@ const posthtml = require('posthtml');
34
43
const posthtmlWebp = require (' posthtml-webp' );
35
44
36
45
posthtml ()
37
- .use (posthtmlWebp ())
46
+ .use (posthtmlWebp (/* Plugin options */ ))
38
47
.process (html/* , options */ )
39
48
.then (result => fs .writeFileSync (' ./after.html' , result .html ));
40
49
```
Original file line number Diff line number Diff line change 1
1
'use strict'
2
2
3
- module . exports = function ( ) {
3
+ module . exports = function ( options ) {
4
+ if ( ! options ) {
5
+ options = { }
6
+ }
7
+
8
+ if ( options . replaceExtension === undefined ) {
9
+ options . replaceExtension = false
10
+ }
11
+
4
12
return function posthtmlWebp ( tree ) {
5
13
tree . match ( { tag : 'img' } , function ( imgNode ) {
6
14
if ( imgNode . skip ) return imgNode
7
- return getPicture ( imgNode )
15
+ return getPicture ( imgNode , options )
8
16
} )
9
17
10
18
return tree
11
19
}
12
20
}
13
21
14
- function getPicture ( imgNode ) {
22
+ function removeExtension ( filename ) {
23
+ var extIndex = filename . lastIndexOf ( '.' )
24
+ if ( extIndex === - 1 ) {
25
+ // Filename has no extension
26
+ return filename
27
+ } else {
28
+ return filename . substring ( 0 , extIndex )
29
+ }
30
+ }
31
+
32
+ function getPicture ( imgNode , options ) {
15
33
imgNode . skip = true
34
+
35
+ var src = imgNode . attrs . src
36
+ if ( options . replaceExtension ) {
37
+ src = removeExtension ( src )
38
+ }
39
+ src += '.webp'
40
+
16
41
return {
17
42
tag : 'picture' ,
18
43
content : [
19
44
{
20
45
tag : 'source' ,
21
46
attrs : {
22
47
type : 'image/webp' ,
23
- srcset : imgNode . attrs . src + '.webp'
48
+ srcset : src
24
49
}
25
50
} ,
26
51
imgNode
You can’t perform that action at this time.
0 commit comments