Created
January 25, 2021 12:45
-
-
Save twslade/6a8eb90eb06b8ed1c19385ad2f9f2588 to your computer and use it in GitHub Desktop.
Custom loader for gatsby images in storybook
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const path = require("path"); | |
const loaderUtils = require("loader-utils"); | |
const { fluid, fixed } = require("gatsby-plugin-sharp/index"); | |
function getFileObject(absolutePath, hash, name, extension) { | |
return { | |
id: `${absolutePath}${hash}`, | |
name: name, | |
absolutePath, | |
extension, | |
internal: { | |
contentDigest: hash | |
} | |
}; | |
} | |
const addPrefix = args => | |
process.env.PATH_PREFIX | |
? { ...args, pathPrefix: process.env.PATH_PREFIX } | |
: args; | |
exports.default = function(content) { | |
/** | |
* Different alias names used to keep Fixed and Fluid image types safe. | |
* See ../../src/images/images.d.ts | |
*/ | |
const loaderName = this._module.rawRequest.split("!")[0]; | |
const isFixed = loaderName === "gatsby-image-fixed"; | |
const args = addPrefix(loaderUtils.parseQuery(this.resourceQuery || "?")); | |
const callback = this.async(); | |
const extension = path.extname(this.resourcePath).replace(/\./, ""); | |
const name = path | |
.basename(this.resourcePath) | |
.replace(path.extname(this.resourcePath), ""); | |
/** | |
* No need to worry about cache. | |
* Generate similar to Gatsby https://github.com/gatsbyjs/gatsby/blob/494ad071f0428b04d35f6e813a603bf8e3b78cac/packages/gatsby-plugin-sharp/src/process-file.js#L234 | |
*/ | |
const hashDigest = loaderUtils.getHashDigest(content, "md5", "hex", 100); | |
const file = getFileObject(this.resourcePath, hashDigest, name, extension); | |
const processedFile = isFixed ? fixed({ file, args }) : fluid({ file, args }); | |
processedFile | |
.then(res => { | |
const response = `module.exports = ${JSON.stringify(res)};`; | |
return callback(null, response); | |
}) | |
.catch(err => console.log(`Error: ${err}`)); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment