Skip to content

Instantly share code, notes, and snippets.

@ionutmilica
Created August 24, 2017 12:13
Show Gist options
  • Select an option

  • Save ionutmilica/23db1a0e449fec32641246bce064f070 to your computer and use it in GitHub Desktop.

Select an option

Save ionutmilica/23db1a0e449fec32641246bce064f070 to your computer and use it in GitHub Desktop.
Laravel Mix in Express (node) apps
const path = require('path');
const { mixFn } = require('./mix');
// mixFn will parse and store the manifest file internally
// it returns a new
const mix = mixFn(path.join(__dirname, 'public')); // where laravel-mix generates the manifest and hot files
console.log(mix('/css/app.css')); // /css/app.css?id=2995d68b12d2d1326355
console.log(mix('/js/js.css')); // /js/app.js?id=87e01f645f82f2f01ab3
// This is a typescript file. You can convert it to javascript online
import * as fs from 'fs';
/**
* Creates a new mix handler
*
* @param rootPath
* @param manifestDirectory
* @returns {Function}
*/
export const mixFn = (
rootPath: string,
manifestDirectory: string = '',
): ((path: string) => string) => {
const publicDir = '/public';
if (manifestDirectory.length > 0 && !manifestDirectory.startsWith('/')) {
manifestDirectory = `/${manifestDirectory}`;
}
const manifestPath = `${rootPath}${publicDir}${manifestDirectory}/mix-manifest.json`;
const isHot: boolean = fs.existsSync(`${rootPath}${publicDir}${manifestDirectory}/hot`);
if (!fs.existsSync(manifestPath)) {
throw new Error(`Cannot find manifest file at ${manifestPath}`);
}
const manifest: any = JSON.parse(fs.readFileSync(manifestPath, 'utf8'));
return (path: string): string => {
if (!path.startsWith('/')) {
path = `/${path}`;
}
if (!manifest[path]) {
throw new Error(
`Unable to locate Mix file: ${path}. Please check your webpack.mix.js output paths and try again.`,
);
}
return isHot
? `http://localhost:8080${manifest[path]}`
: `${manifestDirectory}${manifest[path]}`;
};
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment