-
-
Save b2whats/440351e17dcc14bca00cca9075c9aff6 to your computer and use it in GitHub Desktop.
universal
This file contains 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
import {readFileSync} from 'fs'; | |
import {hook} from 'node-hook'; | |
import {interpolateName} from 'loader-utils'; | |
import { webpackConfig, webpackStatsFile } from '../config'; | |
function readStats() { | |
const stats = require(webpackStatsFile); | |
if (__DEVELOPMENT__) { | |
delete require.cache[require.resolve(webpackStatsFile)]; | |
} | |
return stats; | |
} | |
function calcImageHash(source, resourcePath) { | |
const content = readFileSync(resourcePath); | |
const webpackName = interpolateName({resourcePath}, '[hash].[ext]', {content}); | |
return `module.exports = ${JSON.stringify(webpackConfig.output.publicPath + webpackName)};`; | |
} | |
function getCssStyles(source, resourcePath) { | |
const styles = readStats().css.modules[resourcePath.slice(__dirname.length)]; | |
return `module.exports = ${JSON.stringify(styles)};`; | |
} | |
export function universalImageLoader(ext) { | |
hook(ext, calcImageHash); | |
} | |
export function universalCssLoader(ext) { | |
hook(ext, getCssStyles); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
const readStats = () => {
// don't cache the
webpack-stats.json
on dev so we read the file on each request.// on production, use simple
require
to cache the fileconst stats = require('../webpack-stats.json');
if (DEVELOPMENT) {
delete require.cache[require.resolve('../webpack-stats.json')];
}
return stats;
};
export function requireServerCss(cssPath) {
if (CLIENT) {
throw new Error('server-side only css resolver called on client');
}
return readStats().css.modules[cssPath.slice(__dirname.length)];
}
export function requireServerImage(imagePath) {
if (!imagePath) {
return '';
}
if (CLIENT) {
throw new Error('server-side only image resolver called on client');
}
const images = readStats().images;
if (!images) {
return '';
}
// Find the correct image
const regex = new RegExp(
${imagePath}$
);const image = images.find(img => regex.test(img.original));
// Serve image.
if (image) return image.compiled;
// Serve a not-found asset maybe?
return '';
}