Skip to content

Commit 9921f53

Browse files
author
Simone Sestito
committed
feat: Replace file extension instead of appending .webp
1 parent c53c66e commit 9921f53

File tree

2 files changed

+39
-5
lines changed

2 files changed

+39
-5
lines changed

README.md

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,15 @@ After:
2626

2727
> npm i posthtml posthtml-webp
2828
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+
2938
## Usage
3039

3140
``` js
@@ -34,7 +43,7 @@ const posthtml = require('posthtml');
3443
const posthtmlWebp = require('posthtml-webp');
3544

3645
posthtml()
37-
.use(posthtmlWebp())
46+
.use(posthtmlWebp(/* Plugin options */))
3847
.process(html/*, options */)
3948
.then(result => fs.writeFileSync('./after.html', result.html));
4049
```

lib/index.js

Lines changed: 29 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,26 +1,51 @@
11
'use strict'
22

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+
412
return function posthtmlWebp (tree) {
513
tree.match({ tag: 'img' }, function (imgNode) {
614
if (imgNode.skip) return imgNode
7-
return getPicture(imgNode)
15+
return getPicture(imgNode, options)
816
})
917

1018
return tree
1119
}
1220
}
1321

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) {
1533
imgNode.skip = true
34+
35+
var src = imgNode.attrs.src
36+
if (options.replaceExtension) {
37+
src = removeExtension(src)
38+
}
39+
src += '.webp'
40+
1641
return {
1742
tag: 'picture',
1843
content: [
1944
{
2045
tag: 'source',
2146
attrs: {
2247
type: 'image/webp',
23-
srcset: imgNode.attrs.src + '.webp'
48+
srcset: src
2449
}
2550
},
2651
imgNode

0 commit comments

Comments
 (0)