Skip to content

Instantly share code, notes, and snippets.

@b2whats
Created May 2, 2016 13:18
Show Gist options
  • Save b2whats/440351e17dcc14bca00cca9075c9aff6 to your computer and use it in GitHub Desktop.
Save b2whats/440351e17dcc14bca00cca9075c9aff6 to your computer and use it in GitHub Desktop.
universal
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);
}
@b2whats
Copy link
Author

b2whats commented May 2, 2016

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;
}

@b2whats
Copy link
Author

b2whats commented May 2, 2016

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 '';
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment