-
-
Save b2whats/440351e17dcc14bca00cca9075c9aff6 to your computer and use it in GitHub Desktop.
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); | |
} |
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 file
const 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 '';
}
formatUrl(path) {
let adjustedPath = path[0] !== '/' ? '/' + path : path;
if (SERVER) {
// Prepend host and port of the API server to the path.
return 'http://localhost:' + 3002 + adjustedPath;
}
// Prepend
/api
to relative URL, to proxy to API server.return '/api' + adjustedPath;
}