diff --git a/packages/gatsby-source-filesystem/src/extend-file-node.js b/packages/gatsby-source-filesystem/src/extend-file-node.js new file mode 100644 index 0000000000000..99bf81a29a2ad --- /dev/null +++ b/packages/gatsby-source-filesystem/src/extend-file-node.js @@ -0,0 +1,44 @@ +const { GraphQLString } = require(`graphql`) +const fs = require(`fs-extra`) +const path = require(`path`) + +module.exports = ({ type, getNodeAndSavePathDependency, pathPrefix = `` }) => { + if (type.name !== `File`) { + return {} + } + + return { + publicURL: { + type: GraphQLString, + args: {}, + resolve: (file, fieldArgs, context) => { + const details = getNodeAndSavePathDependency(file.id, context.path) + const fileName = `${file.name}-${file.internal.contentDigest}${ + details.ext + }` + + const publicPath = path.join( + process.cwd(), + `public`, + `static`, + fileName + ) + + if (!fs.existsSync(publicPath)) { + fs.copy(details.absolutePath, publicPath, err => { + if (err) { + console.error( + `error copying file from ${ + details.absolutePath + } to ${publicPath}`, + err + ) + } + }) + } + + return `${pathPrefix}/static/${fileName}` + }, + }, + } +} diff --git a/packages/gatsby-source-filesystem/src/gatsby-node.js b/packages/gatsby-source-filesystem/src/gatsby-node.js index 7cb1a9e8b3cea..0ef8ee9436cdd 100644 --- a/packages/gatsby-source-filesystem/src/gatsby-node.js +++ b/packages/gatsby-source-filesystem/src/gatsby-node.js @@ -95,3 +95,5 @@ Please pick a path to an existing directory. }) }) } + +exports.setFieldsOnGraphQLNodeType = require(`./extend-file-node`) diff --git a/packages/gatsby-transformer-sharp/src/extend-node-type.js b/packages/gatsby-transformer-sharp/src/extend-node-type.js index ace0414f57fd0..779d2f136f463 100644 --- a/packages/gatsby-transformer-sharp/src/extend-node-type.js +++ b/packages/gatsby-transformer-sharp/src/extend-node-type.js @@ -115,17 +115,25 @@ module.exports = ({ type, pathPrefix, getNodeAndSavePathDependency }) => { async resolve(image, fieldArgs, context) { const details = getNodeAndSavePathDependency(image.parent, context.path) const dimensions = sizeOf(details.absolutePath) - const imageName = `${image.internal.contentDigest}${details.ext}` + const imageName = `${details.name}-${image.internal.contentDigest}${ + details.ext + }` const publicPath = path.join( process.cwd(), `public`, - `static/${imageName}` + `static`, + imageName ) if (!fsExtra.existsSync(publicPath)) { fsExtra.copy(details.absolutePath, publicPath, err => { if (err) { - console.error(`error copying file`, err) + console.error( + `error copying file from ${ + details.absolutePath + } to ${publicPath}`, + err + ) } }) } @@ -133,7 +141,7 @@ module.exports = ({ type, pathPrefix, getNodeAndSavePathDependency }) => { return { width: dimensions.width, height: dimensions.height, - src: `/static/` + imageName, + src: `${pathPrefix}/static/${imageName}`, } }, },