Unverified Commit b954bbe6 authored by Steven's avatar Steven Committed by GitHub

fix: codemod `next/image` within monorepo (#46047)

Fix for running the `next/image` codemod within a monorepo

Related to https://twitter.com/codercatdev/status/1625972398448078848

---------
Co-authored-by: 's avatarkodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
parent 2b18d5d6
/**
* @type {import('next').NextConfig}
*/
module.exports = {
reactStrictMode: true,
images: {
loader: "cloudinary",
path: "https://example.com/"
},
async redirects() {
return [
{
source: '/source',
destination: '/dest',
permanent: true,
},
];
},
}
const normalizeSrc = (src) => src[0] === '/' ? src.slice(1) : src
export default function cloudinaryLoader({ src, width, quality }) {
const params = ['f_auto', 'c_limit', 'w_' + width, 'q_' + (quality || 'auto')]
const paramsString = params.join(',') + '/'
return 'https://example.com/' + paramsString + normalizeSrc(src)
}
\ No newline at end of file
/**
* @type {import('next').NextConfig}
*/
module.exports = {
reactStrictMode: true,
images: {
loader: "custom",
loaderFile: "./cloudinary-loader.js"
},
async redirects() {
return [
{
source: '/source',
destination: '/dest',
permanent: true,
},
];
},
}
module.exports = {
images: {
loader: "imgix",
path: "https://example.com/"
},
}
\ No newline at end of file
module.exports = {
images: {
loader: "cloudinary",
path: "https://example.com/"
},
}
\ No newline at end of file
const normalizeSrc = (src) => src[0] === '/' ? src.slice(1) : src
export default function imgixLoader({ src, width, quality }) {
const url = new URL('https://example.com/' + normalizeSrc(src))
const params = url.searchParams
params.set('auto', params.getAll('auto').join(',') || 'format')
params.set('fit', params.get('fit') || 'max')
params.set('w', params.get('w') || width.toString())
if (quality) { params.set('q', quality.toString()) }
return url.href
}
\ No newline at end of file
module.exports = {
images: {
loader: "custom",
loaderFile: "./imgix-loader.js"
},
}
\ No newline at end of file
const normalizeSrc = (src) => src[0] === '/' ? src.slice(1) : src
export default function cloudinaryLoader({ src, width, quality }) {
const params = ['f_auto', 'c_limit', 'w_' + width, 'q_' + (quality || 'auto')]
const paramsString = params.join(',') + '/'
return 'https://example.com/' + paramsString + normalizeSrc(src)
}
\ No newline at end of file
module.exports = {
images: {
loader: "custom",
loaderFile: "./cloudinary-loader.js"
},
}
\ No newline at end of file
/* global jest */
jest.autoMockOff()
const Runner = require('jscodeshift/dist/Runner');
const { cp, mkdir, rm, readdir, readFile } = require('fs/promises')
const { cp, mkdir, mkdtemp, rm, readdir, readFile, stat } = require('fs/promises')
const { readdirSync } = require('fs')
const { tmpdir } = require('os')
const { join } = require('path')
const fixtureDir = join(__dirname, '..', '__testfixtures__', 'next-image-experimental-loader')
const transform = join(__dirname, '..', 'next-image-experimental.js')
const opts = { recursive: true }
const opts = { recursive: true, force: true }
async function toObj(dir) {
const obj = {}
const files = await readdir(dir)
for (const file of files) {
obj[file] = await readFile(join(dir, file), 'utf8')
const filePath = join(dir, file)
const s = await stat(filePath)
if (s.isDirectory()) {
obj[file] = await toObj(filePath)
} else {
obj[file] = await readFile(filePath, 'utf8')
}
}
return obj
}
it.each(readdirSync(fixtureDir))('should transform loader %s', async (loader) => {
const tmp = await mkdtemp(join(tmpdir(), `next-image-experimental-${loader}-`))
const originalCwd = process.cwd()
try {
await mkdir(join(fixtureDir, 'tmp'), opts)
await cp(join(fixtureDir, loader, 'input'), join(fixtureDir, 'tmp'), opts)
process.chdir(join(fixtureDir, 'tmp'))
await mkdir(tmp, opts)
await cp(join(fixtureDir, loader, 'input'), tmp, opts)
process.chdir(tmp)
const result = await Runner.run(transform, [`.`], {})
expect(result.error).toBe(0)
expect(
await toObj(join(fixtureDir, 'tmp'))
await toObj(tmp)
).toStrictEqual(
await toObj(join(fixtureDir, loader, 'output'))
)
} finally {
await rm(join(fixtureDir, 'tmp'), opts)
await rm(tmp, opts)
process.chdir(originalCwd)
}
})
\ No newline at end of file
import { join, parse } from 'path'
import { writeFileSync } from 'fs'
import type {
API,
......@@ -148,11 +149,15 @@ function findAndReplaceProps(
})
}
function nextConfigTransformer(j: JSCodeshift, root: Collection) {
function nextConfigTransformer(
j: JSCodeshift,
root: Collection,
appDir: string
) {
let pathPrefix = ''
let loaderType = ''
root.find(j.ObjectExpression).forEach((o) => {
const [images] = o.value.properties || []
;(o.value.properties || []).forEach((images) => {
if (
images.type === 'ObjectProperty' &&
images.key.type === 'Identifier' &&
......@@ -188,15 +193,20 @@ function nextConfigTransformer(j: JSCodeshift, root: Collection) {
return true
})
if (loaderType && pathPrefix) {
let filename = `./${loaderType}-loader.js`
const importSpecifier = `./${loaderType}-loader.js`
const filePath = join(appDir, importSpecifier)
properties.push(
j.property('init', j.identifier('loaderFile'), j.literal(filename))
j.property(
'init',
j.identifier('loaderFile'),
j.literal(importSpecifier)
)
)
images.value.properties = properties
const normalizeSrc = `const normalizeSrc = (src) => src[0] === '/' ? src.slice(1) : src`
if (loaderType === 'imgix') {
writeFileSync(
filename,
filePath,
`${normalizeSrc}
export default function imgixLoader({ src, width, quality }) {
const url = new URL('${pathPrefix}' + normalizeSrc(src))
......@@ -213,7 +223,7 @@ function nextConfigTransformer(j: JSCodeshift, root: Collection) {
)
} else if (loaderType === 'cloudinary') {
writeFileSync(
filename,
filePath,
`${normalizeSrc}
export default function cloudinaryLoader({ src, width, quality }) {
const params = ['f_auto', 'c_limit', 'w_' + width, 'q_' + (quality || 'auto')]
......@@ -226,7 +236,7 @@ function nextConfigTransformer(j: JSCodeshift, root: Collection) {
)
} else if (loaderType === 'akamai') {
writeFileSync(
filename,
filePath,
`${normalizeSrc}
export default function akamaiLoader({ src, width, quality }) {
return '${pathPrefix}' + normalizeSrc(src) + '?imwidth=' + width
......@@ -239,6 +249,7 @@ function nextConfigTransformer(j: JSCodeshift, root: Collection) {
}
}
})
})
return root
}
......@@ -250,14 +261,15 @@ export default function transformer(
const j = api.jscodeshift.withParser('tsx')
const root = j(file.source)
const parsed = parse(file.path || '/')
const isConfig =
file.path === 'next.config.js' ||
file.path === 'next.config.ts' ||
file.path === 'next.config.mjs' ||
file.path === 'next.config.cjs'
parsed.base === 'next.config.js' ||
parsed.base === 'next.config.ts' ||
parsed.base === 'next.config.mjs' ||
parsed.base === 'next.config.cjs'
if (isConfig) {
const result = nextConfigTransformer(j, root)
const result = nextConfigTransformer(j, root, parsed.dir)
return result.toSource()
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment