├── .github └── workflows │ └── build.yml ├── .gitignore ├── .npmignore ├── .prettierrc ├── .versionrc.js ├── CHANGELOG.md ├── LICENSE ├── README.md ├── codecov.yaml ├── jest.config.js ├── package.json ├── src ├── __tests__ │ ├── fixtures │ │ ├── content.md │ │ └── correct.html │ └── index.spec.ts └── index.ts ├── tsconfig.json └── yarn.lock /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: build 2 | 3 | on: [push] 4 | 5 | jobs: 6 | test: 7 | runs-on: ubuntu-latest 8 | 9 | strategy: 10 | matrix: 11 | node-version: [12.x] 12 | 13 | steps: 14 | - uses: actions/checkout@v1 15 | - name: Use Node.js ${{ matrix.node-version }} 16 | uses: actions/setup-node@v1 17 | with: 18 | node-version: ${{ matrix.node-version }} 19 | - name: Test 20 | run: | 21 | yarn 22 | yarn test:coverage 23 | - name: upload coverage 24 | uses: codecov/codecov-action@v1 25 | with: 26 | token: ${{ secrets.CODECOV_TOKEN }} 27 | 28 | prettier: 29 | runs-on: ubuntu-latest 30 | 31 | strategy: 32 | matrix: 33 | node-version: [12.x] 34 | 35 | steps: 36 | - uses: actions/checkout@v1 37 | - name: Use Node.js ${{ matrix.node-version }} 38 | uses: actions/setup-node@v1 39 | with: 40 | node-version: ${{ matrix.node-version }} 41 | - name: Prettier Check 42 | run: | 43 | yarn 44 | yarn format --check 45 | 46 | typescript: 47 | 48 | runs-on: ubuntu-latest 49 | 50 | strategy: 51 | matrix: 52 | node-version: [12.x] 53 | 54 | steps: 55 | - uses: actions/checkout@v1 56 | - name: Use Node.js ${{ matrix.node-version }} 57 | uses: actions/setup-node@v1 58 | with: 59 | node-version: ${{ matrix.node-version }} 60 | - name: TypeScript Build 61 | run: | 62 | yarn 63 | yarn build 64 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | npm-debug.log* 5 | yarn-debug.log* 6 | yarn-error.log* 7 | lerna-debug.log* 8 | 9 | lib/ 10 | 11 | # Diagnostic reports (https://nodejs.org/api/report.html) 12 | report.[0-9]*.[0-9]*.[0-9]*.[0-9]*.json 13 | 14 | # Runtime data 15 | pids 16 | *.pid 17 | *.seed 18 | *.pid.lock 19 | 20 | # Directory for instrumented libs generated by jscoverage/JSCover 21 | lib-cov 22 | 23 | # Coverage directory used by tools like istanbul 24 | coverage 25 | *.lcov 26 | 27 | # nyc test coverage 28 | .nyc_output 29 | 30 | # Grunt intermediate storage (https://gruntjs.com/creating-plugins#storing-task-files) 31 | .grunt 32 | 33 | # Bower dependency directory (https://bower.io/) 34 | bower_components 35 | 36 | # node-waf configuration 37 | .lock-wscript 38 | 39 | # Compiled binary addons (https://nodejs.org/api/addons.html) 40 | build/Release 41 | 42 | # Dependency directories 43 | node_modules/ 44 | jspm_packages/ 45 | 46 | # TypeScript v1 declaration files 47 | typings/ 48 | 49 | # TypeScript cache 50 | *.tsbuildinfo 51 | 52 | # Optional npm cache directory 53 | .npm 54 | 55 | # Optional eslint cache 56 | .eslintcache 57 | 58 | # Microbundle cache 59 | .rpt2_cache/ 60 | .rts2_cache_cjs/ 61 | .rts2_cache_es/ 62 | .rts2_cache_umd/ 63 | 64 | # Optional REPL history 65 | .node_repl_history 66 | 67 | # Output of 'npm pack' 68 | *.tgz 69 | 70 | # Yarn Integrity file 71 | .yarn-integrity 72 | 73 | # dotenv environment variables file 74 | .env 75 | .env.test 76 | 77 | # parcel-bundler cache (https://parceljs.org/) 78 | .cache 79 | 80 | # Next.js build output 81 | .next 82 | 83 | # Nuxt.js build / generate output 84 | .nuxt 85 | dist 86 | 87 | # Gatsby files 88 | .cache/ 89 | # Comment in the public line in if your project uses Gatsby and *not* Next.js 90 | # https://nextjs.org/blog/next-9-1#public-directory-support 91 | # public 92 | 93 | # vuepress build output 94 | .vuepress/dist 95 | 96 | # Serverless directories 97 | .serverless/ 98 | 99 | # FuseBox cache 100 | .fusebox/ 101 | 102 | # DynamoDB Local files 103 | .dynamodb/ 104 | 105 | # TernJS port file 106 | .tern-port 107 | -------------------------------------------------------------------------------- /.npmignore: -------------------------------------------------------------------------------- 1 | node_modules/ 2 | __tests__ 3 | -------------------------------------------------------------------------------- /.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "semi": false, 3 | "singleQuote": true, 4 | "trailingComma": "none" 5 | } 6 | -------------------------------------------------------------------------------- /.versionrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | preset: require.resolve('conventional-changelog-conventionalcommits'), 3 | types: [ 4 | { type: 'feat', section: 'Features' }, 5 | { type: 'fix', section: 'Bug Fixes' }, 6 | { type: 'chore', section: 'Chores', hidden: false }, 7 | { type: 'docs', section: 'Document Changes', hidden: false }, 8 | { type: 'refactor', section: 'Refactoring', hidden: false }, 9 | { type: 'test', section: 'Test Improve', hidden: false } 10 | ] 11 | } 12 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Changelog 2 | 3 | All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. 4 | 5 | ## [1.2.0](https://github.com/potato4d/rehype-plugin-image-lazy-loading/compare/v1.1.0...v1.2.0) (2021-02-28) 6 | 7 | 8 | ### Chores 9 | 10 | * Modernize build target ([f4fcd2d](https://github.com/potato4d/rehype-plugin-image-lazy-loading/commit/f4fcd2df87fcbfdfaded2b184c973e55bb2e8c97)) 11 | 12 | ## [1.1.0](https://github.com/potato4d/rehype-plugin-image-lazy-loading/compare/v1.0.3...v1.1.0) (2020-09-20) 13 | 14 | 15 | ### Chores 16 | 17 | * Enable declaration ([a102775](https://github.com/potato4d/rehype-plugin-image-lazy-loading/commit/a102775b0899e0563caeadf5866640b8b014eb36)) 18 | 19 | ### [1.0.3](https://github.com/potato4d/rehype-plugin-image-lazy-loading/compare/v1.0.2...v1.0.3) (2020-09-18) 20 | 21 | 22 | ### Chores 23 | 24 | * Add package keywords ([f15e70d](https://github.com/potato4d/rehype-plugin-image-lazy-loading/commit/f15e70d09c6d5597e0c2f2ba6f42d8e7004b7258)) 25 | 26 | ### [1.0.2](https://github.com/potato4d/rehype-plugin-image-lazy-loading/compare/v1.0.1...v1.0.2) (2020-09-18) 27 | 28 | ### [1.0.1](https://github.com/potato4d/rehype-plugin-image-lazy-loading/compare/v1.0.0...v1.0.1) (2020-09-18) 29 | 30 | 31 | ### Chores 32 | 33 | * Customize standard-version ([d3b4a73](https://github.com/potato4d/rehype-plugin-image-lazy-loading/commit/d3b4a73a2b9a8e4426d9c74df62ebca965e423eb)) 34 | * format changelogs ([8fa7199](https://github.com/potato4d/rehype-plugin-image-lazy-loading/commit/8fa7199e126f0d17ff65572aa2aa7c51ed79a5c1)) 35 | * Remove dryRun flag to .versionsrc.js ([ff52a64](https://github.com/potato4d/rehype-plugin-image-lazy-loading/commit/ff52a64786b6559accfea52b83890c44ff83b421)) 36 | 37 | ## 1.0.0 (2020-09-18) 38 | 39 | ### Features 40 | 41 | * Implement inject loading attribue logic ([b928d49](https://github.com/potato4d/rehype-plugin-image-lazy-loading/commit/b928d49cf1f7b87e97374b63caf320632a5aebf9)) 42 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Takuma HANATANI 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # rehype-plugin-image-native-lazy-loading 2 | 3 | ![build](https://github.com/potato4d/rehype-plugin-image-native-lazy-loading/workflows/build/badge.svg) [![codecov](https://codecov.io/gh/potato4d/rehype-plugin-image-native-lazy-loading/branch/master/graph/badge.svg)](https://codecov.io/gh/potato4d/rehype-plugin-image-native-lazy-loading) ![Version](https://img.shields.io/npm/v/rehype-plugin-image-native-lazy-loading.svg?sanitize=true) 4 | 5 | Native lazy loading plugin for Rehype. 6 | 7 | ## Installation 8 | 9 | ```bash 10 | $ yarn add rehype-plugin-image-native-lazy-loading # or npm install 11 | ``` 12 | 13 | ## Usage 14 | 15 | ### General Use 16 | 17 | 1. Add `loading="lazy"` to your markdown document 18 | 19 | ```javascript 20 | import fs from 'fs' 21 | import lazyLoadPlugin from 'rehype-plugin-image-native-lazy-loading' 22 | import unified from 'unified' 23 | import markdown from 'remark-parse' 24 | import remark2rehype from 'remark-rehype' 25 | import html from 'rehype-stringify' 26 | 27 | async function process(markdown: string) { 28 | return new Promise((resolve, reject) => { 29 | unified() 30 | .use(markdown) 31 | .use(remark2rehype) 32 | .use(lazyLoadPlugin) 33 | .use(html) 34 | .process(markdown, (err, file) => { 35 | if (err) { 36 | return reject(err) 37 | } 38 | return resolve(file.toString()) 39 | }) 40 | }) 41 | } 42 | 43 | async function run() { 44 | const input = `# test 45 | ![potato4d](https://github.com/potato4d.png)` 46 | const output = await process(input) 47 | console.log(output) // `

test

\npotato4d` 48 | } 49 | ``` 50 | 51 | 2. Add `loading="lazy"` to your HTML document 52 | 53 | ```javascript 54 | 55 | import fs from 'fs' 56 | import lazyLoadPlugin from 'rehype-plugin-image-native-lazy-loading' 57 | import unified from 'unified' 58 | import parse from 'rehype-parse' 59 | import slug from 'rehype-slug' 60 | import stringify from 'rehype-stringify' 61 | 62 | async function process(html: string) { 63 | return new Promise((resolve, reject) => { 64 | unified() 65 | .use(parse) 66 | .use(slug) 67 | .use(lazyLoadPlugin) 68 | .use(stringify) 69 | .process(html, (err, file) => { 70 | if (err) { 71 | return reject(err) 72 | } 73 | return resolve(file.toString()) 74 | }) 75 | }) 76 | } 77 | 78 | async function run() { 79 | const input = `

test

\npotato4d` 80 | const output = await process(input) 81 | console.log(output) // `

test

\npotato4d` 82 | 83 | ``` 84 | 85 | ### Used with the Framework 86 | 87 | #### `@nuxt/content` 88 | 89 | in your nuxt.config.js 90 | 91 | ```javascript 92 | export default { 93 | // ... 94 | content: { 95 | markdown: { 96 | rehypePlugins: [ 97 | 'rehype-plugin-image-native-lazy-loading' 98 | ] 99 | } 100 | }, 101 | // ... 102 | } 103 | ``` 104 | 105 | For more information, see [official document](https://content.nuxtjs.org/configuration#markdownrehypeplugins). 106 | 107 | ## Support browsers 108 | 109 | - 19 Sep. 2020 110 | 111 | [![Image from Gyazo](https://i.gyazo.com/ccc6d6f57f0e9599a5b1355a8f1f1e39.png)](https://gyazo.com/ccc6d6f57f0e9599a5b1355a8f1f1e39) 112 | 113 | ## LICENCE 114 | 115 | MIT 116 | -------------------------------------------------------------------------------- /codecov.yaml: -------------------------------------------------------------------------------- 1 | comment: 2 | layout: "reach, diff, flags, files" 3 | behavior: default 4 | require_changes: false # if true: only post the comment if coverage changes 5 | require_base: no # [yes :: must have a base report to post] 6 | require_head: yes # [yes :: must have a head report to post] 7 | branches: null 8 | -------------------------------------------------------------------------------- /jest.config.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | preset: 'ts-jest', 3 | testEnvironment: 'node' 4 | } 5 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "rehype-plugin-image-native-lazy-loading", 3 | "version": "1.2.0", 4 | "main": "lib/index.js", 5 | "repository": "ssh://git@github.com/potato4d/rehype-plugin-image-lazy-loading.git", 6 | "author": "Takuma HANATANI ", 7 | "license": "MIT", 8 | "scripts": { 9 | "build": "tsc", 10 | "format": "yarn prettier './src/**/*.ts'", 11 | "test": "jest", 12 | "test:coverage": "jest --coverage" 13 | }, 14 | "keywords": [ 15 | "remark", 16 | "rehype", 17 | "rehype-plugin", 18 | "lazyload", 19 | "lazy-load" 20 | ], 21 | "devDependencies": { 22 | "@types/hast": "^2.3.1", 23 | "@types/jest": "^26.0.14", 24 | "@types/node": "^14.10.3", 25 | "hast": "^1.0.0", 26 | "jest": "^26.4.2", 27 | "prettier": "^2.1.2", 28 | "rehype": "^11.0.0", 29 | "rehype-stringify": "^8.0.0", 30 | "remark-parse": "^8.0.3", 31 | "remark-rehype": "^7.0.0", 32 | "standard-version": "^9.0.0", 33 | "ts-jest": "^26.3.0", 34 | "typescript": "^4.0.2" 35 | }, 36 | "dependencies": { 37 | "unified": "^9.2.0", 38 | "unist-util-visit": "^2.0.3" 39 | } 40 | } 41 | -------------------------------------------------------------------------------- /src/__tests__/fixtures/content.md: -------------------------------------------------------------------------------- 1 | ### test content 2 | 3 | [![potato4d](https://github.com/potato4d.png)](https://github.com/potato4d) 4 | -------------------------------------------------------------------------------- /src/__tests__/fixtures/correct.html: -------------------------------------------------------------------------------- 1 |

test content

2 |

potato4d

3 | -------------------------------------------------------------------------------- /src/__tests__/index.spec.ts: -------------------------------------------------------------------------------- 1 | import fs from 'fs' 2 | import lazyLoadPlugin from '../' 3 | import unified from 'unified' 4 | import markdown from 'remark-parse' 5 | import remark2rehype from 'remark-rehype' 6 | import html from 'rehype-stringify' 7 | 8 | async function process(rawMarkdown: string) { 9 | return new Promise((resolve, reject) => { 10 | unified() 11 | .use(markdown) 12 | .use(remark2rehype) 13 | .use(lazyLoadPlugin) 14 | .use(html) 15 | .process(rawMarkdown, (err, file) => { 16 | if (err) { 17 | return reject(err) 18 | } 19 | return resolve(file.toString()) 20 | }) 21 | }) 22 | } 23 | 24 | describe('index.ts', () => { 25 | test('変換後の タグに対して loading="lazy" 属性が正しく付与されているか', () => { 26 | const content = fs.readFileSync(`${__dirname}/fixtures/content.md`, { 27 | encoding: 'utf-8' 28 | }) 29 | const correct = fs.readFileSync(`${__dirname}/fixtures/correct.html`, { 30 | encoding: 'utf-8' 31 | }) 32 | return process(content).then((result) => { 33 | expect(result + '\n').toBe(correct) 34 | }) 35 | }) 36 | }) 37 | -------------------------------------------------------------------------------- /src/index.ts: -------------------------------------------------------------------------------- 1 | import { Processor, Transformer } from 'unified' 2 | import { Node } from 'unist' 3 | import visit from 'unist-util-visit' 4 | import hast from 'hast' 5 | 6 | function lazyloadPlugin(this: Processor): Transformer { 7 | function visitor(el: hast.Element) { 8 | if (el.tagName !== 'img') { 9 | return 10 | } 11 | el.properties = { 12 | ...(el.properties || {}), 13 | loading: 'lazy' 14 | } 15 | } 16 | 17 | function transformer(htmlAST: Node): Node { 18 | visit(htmlAST, 'element', visitor) 19 | return htmlAST 20 | } 21 | 22 | return transformer 23 | } 24 | 25 | export default lazyloadPlugin 26 | module.exports = lazyloadPlugin 27 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | /* Visit https://aka.ms/tsconfig.json to read more about this file */ 4 | 5 | /* Basic Options */ 6 | // "incremental": true, /* Enable incremental compilation */ 7 | "target": "es2016", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */ 8 | "module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */ 9 | // "lib": [], /* Specify library files to be included in the compilation. */ 10 | // "allowJs": true, /* Allow javascript files to be compiled. */ 11 | // "checkJs": true, /* Report errors in .js files. */ 12 | // "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */ 13 | "declaration": true, /* Generates corresponding '.d.ts' file. */ 14 | // "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */ 15 | // "sourceMap": true, /* Generates corresponding '.map' file. */ 16 | // "outFile": "./", /* Concatenate and emit output to single file. */ 17 | "outDir": "./lib", /* Redirect output structure to the directory. */ 18 | // "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */ 19 | // "composite": true, /* Enable project compilation */ 20 | // "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */ 21 | // "removeComments": true, /* Do not emit comments to output. */ 22 | // "noEmit": true, /* Do not emit outputs. */ 23 | // "importHelpers": true, /* Import emit helpers from 'tslib'. */ 24 | // "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */ 25 | // "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */ 26 | 27 | /* Strict Type-Checking Options */ 28 | "strict": true, /* Enable all strict type-checking options. */ 29 | // "noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */ 30 | // "strictNullChecks": true, /* Enable strict null checks. */ 31 | // "strictFunctionTypes": true, /* Enable strict checking of function types. */ 32 | // "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */ 33 | // "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */ 34 | // "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */ 35 | // "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */ 36 | 37 | /* Additional Checks */ 38 | // "noUnusedLocals": true, /* Report errors on unused locals. */ 39 | // "noUnusedParameters": true, /* Report errors on unused parameters. */ 40 | // "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */ 41 | // "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */ 42 | 43 | /* Module Resolution Options */ 44 | // "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */ 45 | // "baseUrl": "./", /* Base directory to resolve non-absolute module names. */ 46 | // "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */ 47 | // "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */ 48 | // "typeRoots": [], /* List of folders to include type definitions from. */ 49 | // "types": [], /* Type declaration files to be included in compilation. */ 50 | // "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */ 51 | "esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */ 52 | // "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */ 53 | // "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */ 54 | 55 | /* Source Map Options */ 56 | // "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */ 57 | // "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */ 58 | // "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */ 59 | // "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */ 60 | 61 | /* Experimental Options */ 62 | // "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */ 63 | // "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */ 64 | 65 | /* Advanced Options */ 66 | "skipLibCheck": true, /* Skip type checking of declaration files. */ 67 | "forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */ 68 | }, 69 | "exclude": [ 70 | "src/__tests__" 71 | ] 72 | } 73 | --------------------------------------------------------------------------------