Skip to content

Commit

Permalink
feat: staticFilename option to customize static image filenames (#220)
Browse files Browse the repository at this point in the history
Co-authored-by: Pooya Parsa <pyapar@gmail.com>
  • Loading branch information
jdempster and pi0 committed Apr 22, 2021
1 parent 6dc8aa0 commit 975b1a2
Show file tree
Hide file tree
Showing 5 changed files with 37 additions and 12 deletions.
19 changes: 19 additions & 0 deletions docs/content/en/3.api/1.options.md
Original file line number Diff line number Diff line change
Expand Up @@ -148,3 +148,22 @@ export default {
}
```

## `staticFilename`

You can use this option to change filename and location for the static image generation.

### Parameters

- `[name]`: Only filename, without extension or path
- `[hash]`: The hash of url
- `[ext]`: Extension with leading dot `.png`
- `[publicPath]`: Default is `build.publicPath` (`/_nuxt`)

```ts [nuxt.config.js]
export default {
image: {
// Generate images to `/_nuxt/image/file.png`
staticFilename: '[publicPath]/images/[name]-[hash][ext]'
}
}
```
19 changes: 13 additions & 6 deletions src/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ import { createWriteStream } from 'fs'
import { promisify } from 'util'
import stream from 'stream'
import { mkdirp } from 'fs-extra'
import { dirname, join, relative, resolve, extname } from 'upath'
import { dirname, join, relative, extname, basename, trimExt } from 'upath'
import fetch from 'node-fetch'
import { joinURL, hasProtocol, parseURL } from 'ufo'
import { joinURL, hasProtocol, parseURL, withoutTrailingSlash } from 'ufo'
import pLimit from 'p-limit'
import { ModuleOptions, MapToStatic, ResolvedImage } from './types'
import { hash, logger } from './utils'
Expand All @@ -19,15 +19,22 @@ export function setupStaticGeneration (nuxt: any, options: ModuleOptions) {
renderContext.image = renderContext.image || {}
renderContext.image.mapToStatic = <MapToStatic> function ({ url, format }: ResolvedImage) {
if (!staticImages[url]) {
const ext = (format && `.${format}`) || extname(parseURL(url).pathname) || '.png'
staticImages[url] = hash(url) + ext
const { pathname } = parseURL(url)
const params: any = {
name: trimExt(basename(pathname)),
ext: (format && `.${format}`) || extname(pathname) || '.png',
hash: hash(url),
// TODO: pass from runtimeConfig to mapStatic as param
publicPath: withoutTrailingSlash(nuxt.options.build.publicPath)
}

staticImages[url] = options.staticFilename.replace(/\[(\w+)]/g, (match, key) => params[key] || match)
}
return staticImages[url]
}
})

nuxt.hook('generate:done', async () => {
const { dir: generateDir } = nuxt.options.generate
const limit = pLimit(8)
const downloads = Object.entries(staticImages).map(([url, name]) => {
if (!hasProtocol(url)) {
Expand All @@ -36,7 +43,7 @@ export function setupStaticGeneration (nuxt: any, options: ModuleOptions) {
return limit(() => downloadImage({
url,
name,
outDir: resolve(generateDir, '_nuxt/image' /* TODO: staticImagesBase */)
outDir: nuxt.options.generate.dir
}))
})
await Promise.all(downloads)
Expand Down
3 changes: 2 additions & 1 deletion src/module.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { resolve } from 'upath'
import { resolve, join } from 'upath'

import type { Module } from '@nuxt/types'
import defu from 'defu'
Expand All @@ -13,6 +13,7 @@ const imageModule: Module<ModuleOptions> = async function imageModule (moduleOpt
const { nuxt, addPlugin, addServerMiddleware } = this

const defaults: ModuleOptions = {
staticFilename: '[publicPath]/image/[hash][ext]',
provider: 'auto',
presets: {},
dir: resolve(nuxt.options.srcDir, nuxt.options.dir.static),
Expand Down
7 changes: 2 additions & 5 deletions src/runtime/image.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import defu from 'defu'
import { joinURL } from 'ufo'
import type { ImageOptions, ImageSizesOptions, CreateImageOptions, ResolvedImage, MapToStatic, ImageCTX, $Img } from '../types/image'
import { imageMeta } from './utils/meta'
import { parseSize } from './utils'
Expand Down Expand Up @@ -33,11 +32,9 @@ export function createImage (globalOptions: CreateImageOptions, nuxtContext: any

function handleStaticImage (image: ResolvedImage, input: string) {
if (process.static) {
const staticImagesBase = '/_nuxt/image' // TODO

if (process.client && 'fetchPayload' in window.$nuxt) {
const mappedURL = staticImageManifest[image.url]
image.url = mappedURL ? joinURL(staticImagesBase, mappedURL) : input
image.url = mappedURL || input
return image
}

Expand All @@ -50,7 +47,7 @@ export function createImage (globalOptions: CreateImageOptions, nuxtContext: any
const mappedURL = mapToStatic(image)
if (mappedURL) {
staticImages[image.url] = mappedURL
image.url = joinURL(staticImagesBase, mappedURL)
image.url = mappedURL
}
}
}
Expand Down
1 change: 1 addition & 0 deletions src/types/module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export interface ImageProviders {

// TODO: use types from CreateImageOptions
export interface ModuleOptions extends ImageProviders {
staticFilename: string,
provider: CreateImageOptions['provider']
presets: { [name: string]: ImageOptions }
dir: string
Expand Down

0 comments on commit 975b1a2

Please sign in to comment.