Created
March 5, 2019 09:49
-
-
Save koyta/59408f8b927eac15ecc0ee02e9892c1f to your computer and use it in GitHub Desktop.
cra server/index.js
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
const md5File = require('md5-file'); | |
const path = require('path'); | |
const sass = require('node-sass'); | |
// CSS styles will be imported on load and that complicates matters... ignore those bad boys! | |
const ignoreStyles = require('ignore-styles'); | |
const register = ignoreStyles.default; | |
// We also want to ignore all image requests | |
// When running locally these will load from a standard import | |
// When running on the server, we want to load via their hashed version in the build folder | |
const extensions = ['.gif', '.jpeg', '.jpg', '.png', '.svg']; | |
// Override the default style ignorer, also modifying all image requests | |
register(ignoreStyles.DEFAULT_EXTENSIONS, (mod, filename) => { | |
if (!extensions.find(f => filename.endsWith(f))) { | |
// If we find a style | |
return ignoreStyles.noOp(); | |
} else { | |
// If we find an image | |
const hash = md5File.sync(filename).slice(0, 8); | |
const bn = path.basename(filename).replace(/(\.\w{3})$/, `.${hash}$1`); | |
mod.exports = `/static/media/${bn}`; | |
} | |
}); | |
function processSass(data, filename) { | |
var result; | |
result = sass.renderSync({ | |
data: data, | |
file: filename, | |
}).css; | |
return result.toString('utf8'); | |
} | |
// Set up babel to do its thing... env for the latest toys, react-app for CRA | |
// Notice three plugins: the first two allow us to use import rather than require, the third is for code splitting | |
// Polyfill is required for Babel 7, polyfill includes a custom regenerator runtime and core-js | |
require('@babel/polyfill'); | |
require('@babel/register')({ | |
ignore: [/\/(build|node_modules)\//], | |
presets: ['@babel/preset-env', '@babel/preset-react', '@babel/preset-typescript'], | |
plugins: [ | |
'@babel/plugin-transform-modules-commonjs', | |
'@babel/proposal-object-rest-spread', | |
'@babel/syntax-dynamic-import', | |
'babel-plugin-dynamic-import-node', | |
'react-loadable/babel', | |
[ | |
'babel-plugin-css-modules-transform', | |
{ | |
extensions: ['.scss', '.sass'], | |
preprocessCss: processSass, | |
generateScopedName: '[local]__[hash:base64:5]', | |
}, | |
], | |
], | |
}); | |
// Now that the nonsense is over... load up the server entry point | |
require('./server'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment