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 */ /* global jest */
jest.autoMockOff() jest.autoMockOff()
const Runner = require('jscodeshift/dist/Runner'); 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 { readdirSync } = require('fs')
const { tmpdir } = require('os')
const { join } = require('path') const { join } = require('path')
const fixtureDir = join(__dirname, '..', '__testfixtures__', 'next-image-experimental-loader') const fixtureDir = join(__dirname, '..', '__testfixtures__', 'next-image-experimental-loader')
const transform = join(__dirname, '..', 'next-image-experimental.js') const transform = join(__dirname, '..', 'next-image-experimental.js')
const opts = { recursive: true } const opts = { recursive: true, force: true }
async function toObj(dir) { async function toObj(dir) {
const obj = {} const obj = {}
const files = await readdir(dir) const files = await readdir(dir)
for (const file of files) { 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 return obj
} }
it.each(readdirSync(fixtureDir))('should transform loader %s', async (loader) => { 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 { try {
await mkdir(join(fixtureDir, 'tmp'), opts) await mkdir(tmp, opts)
await cp(join(fixtureDir, loader, 'input'), join(fixtureDir, 'tmp'), opts) await cp(join(fixtureDir, loader, 'input'), tmp, opts)
process.chdir(join(fixtureDir, 'tmp')) process.chdir(tmp)
const result = await Runner.run(transform, [`.`], {}) const result = await Runner.run(transform, [`.`], {})
expect(result.error).toBe(0) expect(result.error).toBe(0)
expect( expect(
await toObj(join(fixtureDir, 'tmp')) await toObj(tmp)
).toStrictEqual( ).toStrictEqual(
await toObj(join(fixtureDir, loader, 'output')) await toObj(join(fixtureDir, loader, 'output'))
) )
} finally { } 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 { writeFileSync } from 'fs'
import type { import type {
API, API,
...@@ -148,11 +149,15 @@ function findAndReplaceProps( ...@@ -148,11 +149,15 @@ function findAndReplaceProps(
}) })
} }
function nextConfigTransformer(j: JSCodeshift, root: Collection) { function nextConfigTransformer(
j: JSCodeshift,
root: Collection,
appDir: string
) {
let pathPrefix = '' let pathPrefix = ''
let loaderType = '' let loaderType = ''
root.find(j.ObjectExpression).forEach((o) => { root.find(j.ObjectExpression).forEach((o) => {
const [images] = o.value.properties || [] ;(o.value.properties || []).forEach((images) => {
if ( if (
images.type === 'ObjectProperty' && images.type === 'ObjectProperty' &&
images.key.type === 'Identifier' && images.key.type === 'Identifier' &&
...@@ -188,15 +193,20 @@ function nextConfigTransformer(j: JSCodeshift, root: Collection) { ...@@ -188,15 +193,20 @@ function nextConfigTransformer(j: JSCodeshift, root: Collection) {
return true return true
}) })
if (loaderType && pathPrefix) { if (loaderType && pathPrefix) {
let filename = `./${loaderType}-loader.js` const importSpecifier = `./${loaderType}-loader.js`
const filePath = join(appDir, importSpecifier)
properties.push( properties.push(
j.property('init', j.identifier('loaderFile'), j.literal(filename)) j.property(
'init',
j.identifier('loaderFile'),
j.literal(importSpecifier)
)
) )
images.value.properties = properties images.value.properties = properties
const normalizeSrc = `const normalizeSrc = (src) => src[0] === '/' ? src.slice(1) : src` const normalizeSrc = `const normalizeSrc = (src) => src[0] === '/' ? src.slice(1) : src`
if (loaderType === 'imgix') { if (loaderType === 'imgix') {
writeFileSync( writeFileSync(
filename, filePath,
`${normalizeSrc} `${normalizeSrc}
export default function imgixLoader({ src, width, quality }) { export default function imgixLoader({ src, width, quality }) {
const url = new URL('${pathPrefix}' + normalizeSrc(src)) const url = new URL('${pathPrefix}' + normalizeSrc(src))
...@@ -213,7 +223,7 @@ function nextConfigTransformer(j: JSCodeshift, root: Collection) { ...@@ -213,7 +223,7 @@ function nextConfigTransformer(j: JSCodeshift, root: Collection) {
) )
} else if (loaderType === 'cloudinary') { } else if (loaderType === 'cloudinary') {
writeFileSync( writeFileSync(
filename, filePath,
`${normalizeSrc} `${normalizeSrc}
export default function cloudinaryLoader({ src, width, quality }) { export default function cloudinaryLoader({ src, width, quality }) {
const params = ['f_auto', 'c_limit', 'w_' + width, 'q_' + (quality || 'auto')] const params = ['f_auto', 'c_limit', 'w_' + width, 'q_' + (quality || 'auto')]
...@@ -226,7 +236,7 @@ function nextConfigTransformer(j: JSCodeshift, root: Collection) { ...@@ -226,7 +236,7 @@ function nextConfigTransformer(j: JSCodeshift, root: Collection) {
) )
} else if (loaderType === 'akamai') { } else if (loaderType === 'akamai') {
writeFileSync( writeFileSync(
filename, filePath,
`${normalizeSrc} `${normalizeSrc}
export default function akamaiLoader({ src, width, quality }) { export default function akamaiLoader({ src, width, quality }) {
return '${pathPrefix}' + normalizeSrc(src) + '?imwidth=' + width return '${pathPrefix}' + normalizeSrc(src) + '?imwidth=' + width
...@@ -239,6 +249,7 @@ function nextConfigTransformer(j: JSCodeshift, root: Collection) { ...@@ -239,6 +249,7 @@ function nextConfigTransformer(j: JSCodeshift, root: Collection) {
} }
} }
}) })
})
return root return root
} }
...@@ -250,14 +261,15 @@ export default function transformer( ...@@ -250,14 +261,15 @@ export default function transformer(
const j = api.jscodeshift.withParser('tsx') const j = api.jscodeshift.withParser('tsx')
const root = j(file.source) const root = j(file.source)
const parsed = parse(file.path || '/')
const isConfig = const isConfig =
file.path === 'next.config.js' || parsed.base === 'next.config.js' ||
file.path === 'next.config.ts' || parsed.base === 'next.config.ts' ||
file.path === 'next.config.mjs' || parsed.base === 'next.config.mjs' ||
file.path === 'next.config.cjs' parsed.base === 'next.config.cjs'
if (isConfig) { if (isConfig) {
const result = nextConfigTransformer(j, root) const result = nextConfigTransformer(j, root, parsed.dir)
return result.toSource() 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