Last active
July 14, 2017 15:20
-
-
Save cletusw/4c91af3b6c31c2f24516798e391f336f to your computer and use it in GitHub Desktop.
Add javascript to be added to the webpack-built JS file directly in your HTML (for declaring dependencies, etc.)
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
/* | |
Usage: | |
// template.html | |
<script type="text/javascript-webpack-header"> | |
console.log('loaded template'); | |
require('./nested.js'); | |
</script> | |
<h1>This is the template</h1> | |
// nested.js | |
console.log('loaded nested.js'); | |
// webpack.config.js module rules | |
{ | |
test: /\.html$/, | |
use: [ | |
'html-webpack-header-loader', | |
'raw-loader', | |
], | |
} | |
results in the <script> tag being removed from the template and included as JS directly in the bundle (resulting in `nested.js` being `require`d and loaded. | |
// template.html built JS file | |
console.log('loaded template'); | |
require('./nested.js'); | |
module.exports = '<h1>This is the template</h1>'; | |
*/ | |
var path = require('path'); | |
var headerRegex = /^\s*<script type="text\/javascript-webpack-header">\n?([\s\S]*?)<\/script>\s*/; | |
module.exports = function(source) { | |
var previousExports = this.exec(source, this.resource); | |
var markup = (previousExports && previousExports.default) ? previousExports.default : previousExports; | |
if (typeof markup !== 'string') { | |
throw new Error('Module ' + path.relative(process.cwd(), this.resource) + ' does not export a string as default.'); | |
} | |
var header = ''; | |
var replacedMarkup = markup.replace(headerRegex, function(match, captureGroup1) { | |
header = captureGroup1; | |
return ''; | |
}); | |
var returnValue = header + 'module.exports = ' + JSON.stringify(replacedMarkup); | |
return returnValue; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment