Skip to content

Commit

Permalink
feat: Replace file extension instead of appending .webp
Browse files Browse the repository at this point in the history
  • Loading branch information
Simone Sestito committed Jul 30, 2019
1 parent c53c66e commit 9921f53
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 5 deletions.
11 changes: 10 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,15 @@ After:

> npm i posthtml posthtml-webp
## Plugin options
`replaceExtension` (boolean)

**Default:** false

Replace the extension of the source image with .webp instead of appending .webp to the original filename

**Example**: image.jpg => image.webp (instead of image.jpg.webp)

## Usage

``` js
Expand All @@ -34,7 +43,7 @@ const posthtml = require('posthtml');
const posthtmlWebp = require('posthtml-webp');

posthtml()
.use(posthtmlWebp())
.use(posthtmlWebp(/* Plugin options */))
.process(html/*, options */)
.then(result => fs.writeFileSync('./after.html', result.html));
```
Expand Down
33 changes: 29 additions & 4 deletions lib/index.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,51 @@
'use strict'

module.exports = function () {
module.exports = function (options) {
if (!options) {
options = {}
}

if (options.replaceExtension === undefined) {
options.replaceExtension = false
}

return function posthtmlWebp (tree) {
tree.match({ tag: 'img' }, function (imgNode) {
if (imgNode.skip) return imgNode
return getPicture(imgNode)
return getPicture(imgNode, options)
})

return tree
}
}

function getPicture (imgNode) {
function removeExtension (filename) {
var extIndex = filename.lastIndexOf('.')
if (extIndex === -1) {
// Filename has no extension
return filename
} else {
return filename.substring(0, extIndex)
}
}

function getPicture (imgNode, options) {
imgNode.skip = true

var src = imgNode.attrs.src
if (options.replaceExtension) {
src = removeExtension(src)
}
src += '.webp'

return {
tag: 'picture',
content: [
{
tag: 'source',
attrs: {
type: 'image/webp',
srcset: imgNode.attrs.src + '.webp'
srcset: src
}
},
imgNode
Expand Down

0 comments on commit 9921f53

Please sign in to comment.