-
Notifications
You must be signed in to change notification settings - Fork 43
Description
i am using typescript to compress image using imagemin and imagemozjpeg.Import stateemnt isn't working. I have seen issue in js that require osn't working. but here i am using import. Why is this issue? i am using imagemin version 9.0.
Following is code and error
import imagemin from 'imagemin'
import imageminMozjpeg from 'imagemin-mozjpeg'
export const compressImage = async (req: Request, res: Response) => {
if (!req.file) {
return res.status(400).send('Upload file (key: file)')
}
const inputFilePath: string = req.file.path
const outputFilePath: string = path.join(
__dirname,
'compressed',
`${req.file.filename}-${req.body.compression}.jpg`,
)
const compressionLevel = req.body.compression || 'medium' // Default to medium if not provided
// Define the quality settings based on the compression level
const compressionSettings: { [key: string]: number } = {
low: 30,
medium: 60,
high: 90,
}
// Validate the compression level
if (!compressionSettings[compressionLevel]) {
return res
.status(400)
.send(
'Invalid compression level. Use low, medium, or high. (key: compression)',
)
}
try {
await imagemin([inputFilePath], {
destination: path.dirname(outputFilePath),
plugins: [
imageminMozjpeg({
quality: '80',
}),
],
})
res.download(outputFilePath, (err) => {
if (err) {
console.error(`Error sending file: ${err.message}`)
return res.status(500).send('Error sending file ' + err.message)
}
// Clean up files after sending
try {
console.log('Removing files:', inputFilePath, outputFilePath)
fs.unlinkSync(inputFilePath) // Remove the uploaded file
fs.unlinkSync(outputFilePath) // Remove the compressed file after download
} catch (cleanupErr) {
const error = cleanupErr as Error
console.error(`Error cleaning up files: ${error.message}`)
}
})
} catch (err) {
const error = err as Error
res.status(500).send(`Error compressing image: ${error.message}`)
}
}
Error
Error [ERR_REQUIRE_ESM]: require() of ES Module D:\tl-tools-backend\node_modules\imagemin\index.js from D:\tl-tools-backend\src\controllers\ImageController.ts not supported.
Instead change the require of index.js in D:\tl-tools-backend\src\controllers\ImageController.ts to a dynamic import() which is available in all CommonJS modules.
at require.extensions. [as .js] (D:\tl-tools-backend\node_modules\ts-node\dist\index.js:851:20)
at Object. (D:\tl-tools-backend\src\controllers\ImageController.ts:43:36)
at m._compile (D:\tl-tools-backend\node_modules\ts-node\dist\index.js:857:29) {
code: 'ERR_REQUIRE_ESM'