Last active
March 25, 2018 19:18
-
-
Save kevzettler/49dcf90f93c893eb46ba1e8076a03d76 to your computer and use it in GitHub Desktop.
How to convert html image src into webpack modules. Script to extract html img src attributes and convert to ES6 imports
This file contains hidden or 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 fs = require('fs') | |
const path = require('path'); | |
let replacingFilePath = process.argv[2]; | |
if(!replacingFilePath){ | |
throw "invalid file path to replace" | |
} | |
let relativeImageDirPath = path.relative(path.dirname(replacingFilePath), `${__dirname}/../src/images`); | |
console.log(relativeImageDirPath); | |
let fileContents = ''; | |
let importHeader = ''; | |
try{ | |
fileContents = fs.readFileSync(replacingFilePath, 'utf8'); | |
}catch(ex){ | |
throw ex; | |
} | |
let newContents = fileContents; | |
const regex = /src\=((\"|\')(images\/)((.+)(\.gif|\.jpeg|\.png|\.jpg)+)(\"|\'))/igm; | |
while (match = regex.exec(fileContents)){ | |
var cleanVarName = match[5].split('.')[0]; | |
importHeader += `import ${cleanVarName} from '${relativeImageDirPath}/${match[4]}'; \n` | |
newContents = newContents.replace(match[1], `{${cleanVarName}}`) | |
} | |
let replacedContents = fileContents | |
newContents = `${importHeader} \n ${newContents}`; | |
fs.writeFile(replacingFilePath, newContents, function(err){ | |
if(err) throw err; | |
console.log("successfully updated images in ", replacingFilePath); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I used this for converting a legacy html site into ES6 Gatsby. This extracts
<img src="path"
and converts it to webpack module includes. I use it likefind ./src -name "*.js" | xargs -L1 node ./scripts/replace_images_with_imports.js