Skip to content

Commit

Permalink
webpack 5
Browse files Browse the repository at this point in the history
  • Loading branch information
dazuaz committed Jul 17, 2021
1 parent dad7403 commit 2d831b7
Show file tree
Hide file tree
Showing 18 changed files with 3,604 additions and 3,487 deletions.
5,886 changes: 3,312 additions & 2,574 deletions package-lock.json

Large diffs are not rendered by default.

4 changes: 2 additions & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@
"@types/find-cache-dir": "^3.2.0",
"@types/jest": "^26.0.23",
"@types/json-schema": "^7.0.7",
"@types/node": "^15.12.0",
"@types/node": "^14.17.0",
"@types/sharp": "^0.28.3",
"@types/webpack": "^5.28.0",
"@typescript-eslint/eslint-plugin": "^4.26.0",
Expand All @@ -71,7 +71,7 @@
"prettier-eslint": "^12.0.0",
"sharp": "^0.28.3",
"typescript": "^4.3.2",
"webpack": "5.37.0",
"webpack": "^5.37.0",
"webpack-cli": "^4.7.0"
},
"jest": {
Expand Down
46 changes: 20 additions & 26 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import { parseOptions, getOutputAndPublicPath, createPlaceholder } from './utils
import { cache } from './cache'
import type { LoaderContext } from 'webpack'

import { interpolateName } from './interpolateName'
import interpolateName from './interpolateName'
import { parseQuery } from './parseQuery'

import type {
Expand Down Expand Up @@ -43,40 +43,36 @@ const DEFAULTS = {
*
* @return {loaderCallback} loaderCallback Result
*/
export default function loader(this: LoaderContext<any>, content: string): void {
export default function loader(this: LoaderContext<Options>, content: string): void {
const loaderCallback = this.async()
if (typeof loaderCallback == 'undefined') {
new Error('Responsive loader callback error')
return
}

// Parsers the query string and options
const parsedResourceQuery = this.resourceQuery ? parseQuery(this.resourceQuery) : {}
// Combines defaults, webpack options and query options,
// later sources' properties overwrite earlier ones.
const options: Options = Object.assign({}, DEFAULTS, this.getOptions(), parsedResourceQuery)
// // Object representation of the query string

// // Combines defaults, webpack options and query options,
// // later sources' properties overwrite earlier ones.
// const options: Options = Object.assign({}, DEFAULTS, getOptions(this), parsedResourceQuery)
// Combines defaults, webpack options and query options,
const options = { ...DEFAULTS, ...this.getOptions(), ...parsedResourceQuery }

validate(schema as JSONSchema7, options, { name: 'Responsive Loader' })

/**
* Parses options and set defaults options
*/
const { outputContext, mime, ext, name, sizes, outputPlaceholder, placeholderSize, imageOptions, cacheOptions } =
parseOptions(this, options)
const outputContext = options.context || this.rootContext
const { mime, ext, name, sizes, outputPlaceholder, placeholderSize, imageOptions, cacheOptions } = parseOptions(
this.resourcePath,
options
)

if (!mime) {
loaderCallback(new Error('No mime type for file with extension ' + ext + ' supported'))
return
}

const createFile = ({ data, width, height }: AdapterResizeResponse) => {
const fileName = interpolateName(this, name, {
const fileName = interpolateName(this.resourcePath, this.resourceQuery, name, {
context: outputContext,
content: data,
content: data.toString(),
})
.replace(/\[width\]/gi, width + '')
.replace(/\[height\]/gi, height + '')
Expand Down Expand Up @@ -114,12 +110,10 @@ export default function loader(this: LoaderContext<any>, content: string): void
)
return
}
/**
* The full config is passed to the adapter, later sources' properties overwrite earlier ones.
*/
// The full config is passed to the adapter, later sources' properties overwrite earlier ones.
const adapterOptions = Object.assign({}, options, imageOptions)

const transformParams: TransformParams = {
const transformParams = {
adapterModule: options.adapter,
resourcePath: this.resourcePath,
adapterOptions,
Expand Down Expand Up @@ -155,8 +149,8 @@ async function orchestrate(params: OrchestrateParams) {
// Transform based on the parameters
export async function transform({
adapterModule,
createFile,
resourcePath,
createFile,
sizes,
mime,
outputPlaceholder,
Expand All @@ -180,16 +174,16 @@ export async function transform({

const srcset = files.map((f) => f.src).join('+","+')
const images = files.map((f) => `{path: ${f.path},width: ${f.width},height: ${f.height}}`).join(',')
const firstImage = files[0]
const defaultImage = outputPlaceholder ? files[files.length - 2] : files[files.length - 1]

return `${esModule ? 'export default' : 'module.exports ='} {
srcSet: ${srcset},
images: [${images}],
src: ${firstImage.path},
toString: function(){return ${firstImage.path}},
src: ${defaultImage.path},
toString: function(){return ${defaultImage.path}},
${placeholder ? 'placeholder: ' + placeholder + ',' : ''}
width: ${firstImage.width},
height: ${firstImage.height}
width: ${defaultImage.width},
height: ${defaultImage.height}
}`
}

Expand Down
28 changes: 12 additions & 16 deletions src/interpolateName.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
'use strict'
import type { LoaderContext } from 'webpack'

import { util } from 'webpack'
import * as path from 'path'

Expand All @@ -8,7 +8,12 @@ type Options = {
content: string
}

function interpolateName(loaderContext: LoaderContext<any>, name: string, options: Options): string {
export default function interpolateName(
loaderResourcePath: string,
loaderResourceQuery: string,
name: string,
options: Options
): string {
const filename = name || '[hash].[ext]'

const context = options.context
Expand All @@ -20,9 +25,9 @@ function interpolateName(loaderContext: LoaderContext<any>, name: string, option
let folder = ''
let query = ''

if (loaderContext.resourcePath) {
const parsed = path.parse(loaderContext.resourcePath)
let resourcePath = loaderContext.resourcePath
if (loaderResourcePath) {
const parsed = path.parse(loaderResourcePath)
let resourcePath = loaderResourcePath

if (parsed.ext) {
ext = parsed.ext.substr(1)
Expand Down Expand Up @@ -50,8 +55,8 @@ function interpolateName(loaderContext: LoaderContext<any>, name: string, option
}
}

if (loaderContext.resourceQuery && loaderContext.resourceQuery.length > 1) {
query = loaderContext.resourceQuery
if (loaderResourceQuery && loaderResourceQuery.length > 1) {
query = loaderResourceQuery

const hashIdx = query.indexOf('#')

Expand Down Expand Up @@ -79,14 +84,5 @@ function interpolateName(loaderContext: LoaderContext<any>, name: string, option
.replace(/\[folder\]/gi, () => folder)
.replace(/\[query\]/gi, () => query)

// if (
// typeof loaderContext.getOptions() === 'object' &&
// typeof loaderContext.getOptions().customInterpolateName === 'function'
// ) {
// url = loaderContext.getOptions().customInterpolateName.call(loaderContext, url, name, options)
// }

return url
}

export { interpolateName }
6 changes: 3 additions & 3 deletions src/types.d.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
declare type Options = {
export type Options = {
size?: string | number
sizes?: [string | number]
min?: string | number
Expand Down Expand Up @@ -44,17 +44,17 @@ export interface AdapterImplementation {
metadata: () => Promise<{ width: number; height: number }>
resize: (config: { width: number; mime: string; options: Options }) => Promise<AdapterResizeResponse>
}
export type AdapterResizeResponse = { data: string; width: number; height: number }
export type AdapterResizeResponse = { data: string | Buffer; width: number; height: number }

export interface TransformParams {
adapterModule: Adapter | undefined
resourcePath: string
createFile: ({ data, width, height }: AdapterResizeResponse) => {
src: string
path: string
width: number
height: number
}
resourcePath: string
outputPlaceholder: boolean
placeholderSize: number
mime: MimeType
Expand Down
10 changes: 2 additions & 8 deletions src/utils.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import * as path from 'path'
import type { Options, MimeType, ImageOptions, CacheOptions } from './types'
import type { LoaderContext } from 'webpack'

const version = '3'

Expand All @@ -20,7 +19,6 @@ enum EXTS {
}

type ParsedOptions = {
outputContext: string
outputPlaceholder: boolean
placeholderSize: number
name: string
Expand All @@ -31,10 +29,7 @@ type ParsedOptions = {
cacheOptions: CacheOptions
}

function parseOptions(loaderContext: LoaderContext<any>, options: Options): ParsedOptions {
const outputContext: string = options.context || loaderContext.rootContext
// <path>/<to>/<folder>/responsive-loader

function parseOptions(resourcePath: string, options: Options): ParsedOptions {
const outputPlaceholder = Boolean(options.placeholder)
const placeholderSize: number = parseInt(options.placeholderSize + '', 10)

Expand All @@ -54,7 +49,7 @@ function parseOptions(loaderContext: LoaderContext<any>, options: Options): Pars
mime = MIMES[options.format]
ext = EXTS[mime]
} else {
ext = path.extname(loaderContext.resourcePath).replace(/\./, '')
ext = path.extname(resourcePath).replace(/\./, '')
switch (ext) {
case 'jpg':
case 'jpeg':
Expand Down Expand Up @@ -98,7 +93,6 @@ function parseOptions(loaderContext: LoaderContext<any>, options: Options): Pars
cacheCompression: Boolean(options.cacheCompression),
}
return {
outputContext,
ext,
mime,
name,
Expand Down
Loading

0 comments on commit 2d831b7

Please sign in to comment.