Skip to content

Commit

Permalink
chore: 0.1.3
Browse files Browse the repository at this point in the history
  • Loading branch information
zkz098 committed Jan 23, 2024
1 parent 6590c91 commit 34d2db9
Show file tree
Hide file tree
Showing 10 changed files with 108 additions and 85 deletions.
21 changes: 21 additions & 0 deletions .eslintrc.cjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
module.exports = {
parser: '@typescript-eslint/parser',
env: {
browser: true,
commonjs: true,
es6: true,
node: true
},
extends: [
'standard',
'plugin:@typescript-eslint/recommended',
],
plugins: [
'@typescript-eslint'
],
parserOptions: {
ecmaVersion: 2022
},
rules: {
}
}
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -6,3 +6,4 @@ npm-debug.log*
*.js
pnpm-lock.yaml
.idea
*.d.ts
31 changes: 15 additions & 16 deletions index.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import type Hexo from 'hexo'
import {minify_html} from "./lib/html";
import {minify_css} from "./lib/css";
import {minify_js} from "./lib/js";
import {replaceSrc, transformImage} from "./lib/img";
import { minifyHtml } from './lib/html'
import { minifyCss } from './lib/css'
import { minifyJs } from './lib/js'
import { replaceSrc, transformImage } from './lib/img'

declare const hexo:Hexo

Expand All @@ -14,23 +14,23 @@ hexo.config.minify.js = Object.assign({
toplevel: false
},
exclude: []
},hexo.config.minify?.js)
}, hexo.config.minify?.js)

hexo.config.minify.css = Object.assign({
enable: true,
options: {
targets: null
},
exclude: []
},hexo.config.minify?.css)
}, hexo.config.minify?.css)

hexo.config.minify.html = Object.assign({
enable: true,
options: {
comments: false
},
exclude: []
},hexo.config.minify?.html)
}, hexo.config.minify?.html)

hexo.config.minify.image = Object.assign({
enable: true,
Expand All @@ -39,24 +39,23 @@ hexo.config.minify.image = Object.assign({
avif: false,
quality: 80,
effort: 2,
replaceSrc: true,
replaceSrc: true
},
exclude: []
},hexo.config.minify?.image)
}, hexo.config.minify?.image)

if (hexo.config.minify.html.enable) {
hexo.extend.filter.register("after_render:html", minify_html)
hexo.extend.filter.register('after_render:html', minifyHtml)
}
if (hexo.config.minify.css.enable) {
hexo.extend.filter.register("after_render:css", minify_css)
if (hexo.config.minify.css.enable) {
hexo.extend.filter.register('after_render:css', minifyCss)
}
if (hexo.config.minify.js.enable) {
hexo.extend.filter.register("after_render:js", minify_js)
hexo.extend.filter.register('after_render:js', minifyJs)
}
if (hexo.config.minify.image.enable) {
hexo.extend.filter.register("after_generate", transformImage, 50)
hexo.extend.filter.register('after_generate', transformImage, 50)
if (hexo.config.minify.image.options.replaceSrc) {
hexo.extend.filter.register("after_render:html", replaceSrc, 1)
hexo.extend.filter.register('after_render:html', replaceSrc, 1)
}
}

18 changes: 9 additions & 9 deletions lib/css.ts
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
import type Hexo from "hexo";
import {isExclude} from "./utils";
import browserslist from 'browserslist';
import {transform,browserslistToTargets} from 'lightningcss'
import type Hexo from 'hexo'
import { isExclude } from './utils'
import browserslist from 'browserslist'
import { transform, browserslistToTargets } from 'lightningcss'
interface CSSMinifyConfig {
enable: boolean
options: {
targets?: string
}
exclude: string[]
}
export function minify_css(this: Hexo,str:string,data:any){
const {options,exclude} = this.config.minify.css as CSSMinifyConfig
export function minifyCss (this: Hexo, str:string, data:any) {
const { options, exclude } = this.config.minify.css as CSSMinifyConfig
const targets = browserslistToTargets(browserslist(options.targets || '>= 0.5%'))
if (!data.path || isExclude(data.path,exclude)) return str
if (isExclude(data.path, exclude)) return str
return transform({
filename: data.path,
code: Buffer.from(str),
minify: true,
targets: targets
targets
}).code.toString()
}
}
16 changes: 8 additions & 8 deletions lib/html.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import {minify} from '@minify-html/node'
import {isExclude} from "./utils";
import type Hexo from "hexo"
import { minify } from '@minify-html/node'
import { isExclude } from './utils'
import type Hexo from 'hexo'

interface HtmlMinifyConfig {
enable: boolean
Expand All @@ -9,11 +9,11 @@ interface HtmlMinifyConfig {
}
exclude: string[]
}
export function minify_html(this: Hexo,str:string,data:any){
const {options,exclude} = this.config.minify.html as HtmlMinifyConfig
if (!data.path || isExclude(data.path,exclude)) return str
return minify(Buffer.from(str),{
export function minifyHtml (this: Hexo, str:string, data:any) {
const { options, exclude } = this.config.minify.html as HtmlMinifyConfig
if (isExclude(data.path, exclude)) return str
return minify(Buffer.from(str), {
keep_spaces_between_attributes: true,
keep_comments: options.comments
}).toString()
}
}
67 changes: 33 additions & 34 deletions lib/img.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import path from "node:path"
import path from 'node:path'
import fs from 'fs/promises'
import sharp from "sharp"
import type Hexo from "hexo";
import {isExclude} from "./utils";
import sharp from 'sharp'
import type Hexo from 'hexo'
import { isExclude } from './utils'
import { load } from 'cheerio'

interface transformImageOptions {
Expand All @@ -17,86 +17,85 @@ interface transformImageOptions {
exclude: string[]
}
export async function transformImage (this: Hexo) {
const publicDir = this.public_dir;
const {options,exclude} = this.config.minify.image as transformImageOptions
const sharpOptions = {
const publicDir = this.public_dir
const { options, exclude } = this.config.minify.image as transformImageOptions
const sharpOptions:Partial<sharp.WebpOptions> = {
effort: options.effort,
lossless: false,
nearLossless: false,
quality: 100
}
if (options.quality === "lossless") {
if (options.quality === 'lossless') {
sharpOptions.lossless = true
} else if (options.quality === "nearLossless") {
} else if (options.quality === 'nearLossless') {
sharpOptions.nearLossless = true
} else {
sharpOptions.quality = options.quality
}

const images = this.route.list().filter(item => item.match(/\.(png|jpg|gif)$/i));
const images = this.route.list().filter(item => item.match(/\.(png|jpg|gif)$/i))
let firstRun = false

await Promise.all(images.map(async imagePath => {
if (isExclude(imagePath,exclude)){
if (isExclude(imagePath, exclude)) {
return
}
const webpPath = imagePath.replace(/\.(png|jpg|gif)$/i, '.webp');
const webpPath = imagePath.replace(/\.(png|jpg|gif)$/i, '.webp')

const sourceImagePath = path.join(publicDir, imagePath);
const webpImagePath = path.join(publicDir, webpPath);
const sourceImagePath = path.join(publicDir, imagePath)
const webpImagePath = path.join(publicDir, webpPath)

if (!(await fs.access(webpImagePath).catch(() => false))) {
await sharp(sourceImagePath)
.webp(sharpOptions)
.toFile(webpImagePath)
.then(info => {
this.log.info(`Converted ${imagePath} to WebP (${info.size} bytes)`);
this.log.info(`Converted ${imagePath} to WebP (${info.size} bytes)`)
})
.catch((err) => {
if (err.toString().indexOf('Input file is missing')!==-1){
if (err.toString().indexOf('Input file is missing') !== -1) {
firstRun = true
} else {
this.log.error(`Error converting ${imagePath} to WebP:`, err);
this.log.error(`Error converting ${imagePath} to WebP:`, err)
}
});
})
}
}));
}))

if (firstRun) {
this.log.warn("The the WebP converter can not run correctly when you run hexo g after hexo cl, please run the hexo g again")
this.log.warn('The the WebP converter can not run correctly when you run hexo g after hexo cl, please run the hexo g again')
}
}

export function replaceSrc(this: Hexo, str:string){
const $ = load(str, { decodeEntities: false });
export function replaceSrc (this: Hexo, str:string) {
const $ = load(str, { decodeEntities: false })
const origin = new URL(this.config.url).origin

function replaceLink(src:string){
function replaceLink (src:string) {
const srcO = path.parse(src)
return path.join(srcO.dir, srcO.name + '.webp').replace(/\\/g, '/')
}

const isLocalLink = (src?:string)=>{
return (src && (src.startsWith('/') || src.startsWith('.') || new URL(src,this.config.url).origin === origin) && /\.(png|jpg|gif)$/.test(src));
const isLocalLink = (src?:string) => {
return (src && (src.startsWith('/') || src.startsWith('.') || new URL(src, this.config.url).origin === origin) && /\.(png|jpg|gif)$/.test(src))
}

$('img').each(function (){
$('img').each(function () {
const img = $(this)
let src = img.attr('src');
let dataSrc = img.attr('data-src');
let dataBgImg = img.attr('data-background-image');
const src = img.attr('src')
const dataSrc = img.attr('data-src')
const dataBgImg = img.attr('data-background-image')

if (isLocalLink(src) && typeof src !== 'undefined') {
img.attr('src',replaceLink(src))
img.attr('src', replaceLink(src))
}
if (isLocalLink(dataSrc) && typeof dataSrc !== 'undefined') {
img.attr('data-src',replaceLink(dataSrc))
img.attr('data-src', replaceLink(dataSrc))
}
if (isLocalLink(dataBgImg) && typeof dataBgImg !== 'undefined') {
img.attr('data-background-image',replaceLink(dataBgImg))
img.attr('data-background-image', replaceLink(dataBgImg))
}

})

return $.html()
}
}
21 changes: 9 additions & 12 deletions lib/js.ts
Original file line number Diff line number Diff line change
@@ -1,19 +1,16 @@
import {transform} from 'esbuild'
import type Hexo from "hexo";
import {isExclude} from "./utils";

import { transform } from 'esbuild'
import type Hexo from 'hexo'
import { isExclude } from './utils'

interface JavascriptMinifyConfig {
enable: boolean
options: {

}
options: unknown
exclude?: string[]
}
export async function minify_js(this: Hexo, str:string,data:any){
const {options,exclude} = this.config.minify.js as JavascriptMinifyConfig
if (!data.path || isExclude(data.path,exclude)) return str
return (await transform(str,{
export async function minifyJs (this: Hexo, str:string, data:any) {
const { exclude } = this.config.minify.js as JavascriptMinifyConfig
if (isExclude(data.path, exclude)) return str
return (await transform(str, {
minify: true
})).code
}
}
6 changes: 3 additions & 3 deletions lib/utils.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import micromatch from "micromatch";
import micromatch from 'micromatch'

export function isExclude(path:string,excludes?:string[]):undefined | boolean {
export function isExclude (path:string, excludes?:string[]):undefined | boolean {
return excludes && excludes.some(item => micromatch.isMatch(path, item, { nocase: true }))
}
}
11 changes: 8 additions & 3 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
{
"name": "hexo-lightning-minify",
"version": "0.1.2",
"version": "0.1.3",
"description": "A Hexo plugin that can automatically minify JS, CSS, and HTML files at lightning speed.",
"main": "index.js",
"scripts": {
"build": "tsc",
"build": "tsc --build --verbose",
"test": "tsc"
},
"author": "zkz098",
Expand All @@ -22,6 +22,11 @@
"typescript": "^5.3.3"
},
"devDependencies": {
"@types/micromatch": "^4.0.6"
"@types/micromatch": "^4.0.6",
"@typescript-eslint/eslint-plugin": "^6.19.0",
"@typescript-eslint/parser": "^6.19.0",
"eslint": "^8.56.0",
"eslint-config-standard": "~17",
"eslint-plugin-n": "^16.6.2"
}
}
1 change: 1 addition & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
"module": "CommonJS",
"removeComments": true,
"strict": true,
"declaration": true,
"esModuleInterop": true,
"moduleResolution": "node",
"skipLibCheck": true
Expand Down

0 comments on commit 34d2db9

Please sign in to comment.