Skip to content

Instantly share code, notes, and snippets.

@zoubin
Created August 7, 2016 16:58
Show Gist options
  • Save zoubin/95f9605a7fd61c863de0a1570eaea8a6 to your computer and use it in GitHub Desktop.
Save zoubin/95f9605a7fd61c863de0a1570eaea8a6 to your computer and use it in GitHub Desktop.
Fix `require` in script tags of pages for electron renderer process
/**
* convert `Shared Folders\projects\electron-quick-start`
* to `Z:\projects\electron-quick-start`
* See https://github.com/electron/electron/issues/6760
*
* Copy the source code to your page
* or add a script tag with src refering to this module
* **BEFORE** any module `require` takes place.
*
* Now you can `require` modules in HTML script tags as you do in node.
*
*/
;(function hackModuleInHtmlForVirtualMachines () {
if (typeof module === 'undefined' || typeof __dirname === 'undefined' || typeof __filename === 'undefined') return
const path = require('path')
// All modules except the main module should return
if (!module.filename || path.isAbsolute(module.filename)) return
// Only the main module should go here
// The root of a normal path: '' or 'Z:'
const root = process.cwd().split(path.sep).shift()
// Virtual machines may have 'Shared Folders' as the root
const VMRoot = __dirname.split(path.sep).shift()
// correct the `__dirname` and `__filename` variable provided to the page
__dirname = root + __dirname.slice(VMRoot.length)
__filename = root + __filename.slice(VMRoot.length)
// Node will use the `filename` and `paths` to locate child modules
module.filename = __filename
if (module.paths) {
const VMPrefixLen = path.resolve(VMRoot).length
module.paths.forEach((p, i) => {
module.paths[i] = root + p.slice(VMPrefixLen)
})
}
})()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment