Skip to content

Instantly share code, notes, and snippets.

@kevzettler
Last active March 25, 2018 19:18
Show Gist options
  • Save kevzettler/49dcf90f93c893eb46ba1e8076a03d76 to your computer and use it in GitHub Desktop.
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
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);
});
@kevzettler
Copy link
Author

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 like

find ./src -name "*.js" | xargs -L1 node ./scripts/replace_images_with_imports.js

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment