html-loader
html-loader copied to clipboard
Allow to inline scripts and styles
would be nice if the loader converted <script src...
and <script>...</script>
to requires.
Not sure how to achieve the multiple javascript output from a single module, though.
+1
+1
You do it like this, for example, for CSS I'm doing.
function extract_css (content, loaderContext) {
try {
const loaderUtils = require('loader-utils');
const posthtml = require('posthtml');
return posthtml()
.use(tree => {
if (tree.length === 0) return tree;
return tree.match([
{ tag: 'style' }
], node => {
if (!node.content) {
node.tag = false;
return node;
}
const content = node.content;
const url = loaderUtils.interpolateName(this, '[hash:24]deadc0de.css', {
content,
});
loaderContext.emitFile(url, content); //here, just emit the file
node.tag = 'link';
node.attrs = {
rel: 'stylesheet',
href: url,
};
node.content = [];
return node;
});
})
.process(content, { sync: true })
.html;
} catch (error) {
loaderContext.emitError(error);
return content;
}
}
function filter_extracted_css (tag, attribute, attributes) {
return !(attributes[attribute] && attributes[attribute].indexOf('deadc0de') !== -1);
}
And then
///webpack.config.js
module: {
rules: [
{
test: /\.css$/,
use: [{
loader: 'file-loader',
}, {
loader: 'extract-loader',
}, {
loader: 'css-loader',
}]
},
{
test: /\.val\.js$/,
use: [{
loader: 'raw-loader',
}, {
loader: 'extract-loader',
}, {
loader: 'html-loader',
options: {
minimize: true,
attributes: {
root: resolve(CONFIG.assetsDir),
list: [
{
tag: 'img',
attribute: 'src',
type: 'src',
filter: util.filter_extracted_file,
},
{
tag: 'link',
attribute: 'href',
type: 'src',
filter: util.filter_extracted_css,
}
],
},
preprocessor: util.extract_css,
}
}, {
loader: 'val-loader',
}]
}
]
},
Caveat, all my resources are public rooted paths like "/something.jpg"