Update server and client configs

This commit is contained in:
LordMathis 2018-12-27 20:24:59 +01:00
parent 7670ade223
commit 741472f668
10 changed files with 178 additions and 227 deletions

View File

@ -4,7 +4,7 @@
"description": "portfolio", "description": "portfolio",
"main": "index.js", "main": "index.js",
"scripts": { "scripts": {
"build": "NODE_ENV=production webpack -p --progress --config webpack.prod.config.js", "build": "NODE_ENV=production webpack -p --progress",
"start": "NODE_ENV=production node ./src/server.js", "start": "NODE_ENV=production node ./src/server.js",
"dev": "NODE_ENV=development babel-node ./src/server.js --presets es2015,stage-2 ./srcserver.js" "dev": "NODE_ENV=development babel-node ./src/server.js --presets es2015,stage-2 ./srcserver.js"
}, },
@ -25,7 +25,8 @@
"node-sass": "^4.9.0", "node-sass": "^4.9.0",
"react": "^16.7.0", "react": "^16.7.0",
"react-dom": "^16.7.0", "react-dom": "^16.7.0",
"react-router-dom": "^4.1.1" "react-router-dom": "^4.1.1",
"webpack-node-externals": "^1.7.2"
}, },
"devDependencies": { "devDependencies": {
"babel-cli": "^6.26.0", "babel-cli": "^6.26.0",

View File

@ -5,7 +5,7 @@ import {App} from './components';
const AppClient = () => ( const AppClient = () => (
<Router> <Router>
<App /> <App data={window.__INITIAL_DATA__}/>
</Router> </Router>
) )

View File

@ -1,16 +1,43 @@
import React from 'react'; import { NotFoundWrapper } from '.'
import { Route, Switch } from 'react-router-dom'; import React, { Component } from 'react'
import { NotFoundWrapper } from '.'; import routes from '../utils/routes'
import { MainContainer, PostContainer } from '../containers'; import { Route, Switch } from 'react-router-dom'
export const App = () => ( class App extends Component {
render() {
return (
<div> <div>
<Switch> <Switch>
<Route exact path="/" component={MainContainer} /> {routes.map(({ path, exact, component: C, ...rest }) => (
<Route path="/post/:postname" component={PostContainer} /> <Route
<Route component={NotFoundWrapper} /> key={path}
path={path}
exact={exact}
render={(props) => (
<C {...props} {...rest} />
)}
/>
))}
<Route render={(props) => <NotFoundWrapper {...props} />} />
</Switch> </Switch>
</div> </div>
); )
}
}
export default App; // import React from 'react';
// import { Route, Switch } from 'react-router-dom';
// import { NotFoundWrapper } from '.';
// import { MainContainer, PostContainer } from '../containers';
//
// export const App = () => (
// <div>
// <Switch>
// <Route exact path="/" component={MainContainer} />
// <Route path="/post/:postname" component={PostContainer} />
// <Route component={NotFoundWrapper} />
// </Switch>
// </div>
// );
//
// export default App;

View File

@ -21,23 +21,23 @@ var dataStub = {"posts": [], "other": []};
fs.writeFileSync(filename, JSON.stringify(dataStub)); fs.writeFileSync(filename, JSON.stringify(dataStub));
// initalize webpack dev middleware if in development context // // initalize webpack dev middleware if in development context
if (process.env.NODE_ENV === 'development') { // if (process.env.NODE_ENV === 'development') {
var webpack = require('webpack') // var webpack = require('webpack')
var config = require('../webpack.config') // var config = require('../webpack.config')
//
var devMiddleware = require('webpack-dev-middleware') // var devMiddleware = require('webpack-dev-middleware')
var hotDevMiddleware = require('webpack-hot-middleware') // var hotDevMiddleware = require('webpack-hot-middleware')
var compiler = webpack(config) // var compiler = webpack(config)
var devMiddlewareConfig = { // var devMiddlewareConfig = {
noInfo: true, // noInfo: true,
stats: {colors: true}, // stats: {colors: true},
publicPath: config.output.publicPath // publicPath: config.output.publicPath
} // }
//
app.use(devMiddleware(compiler, devMiddlewareConfig)) // app.use(devMiddleware(compiler, devMiddlewareConfig))
app.use(hotDevMiddleware(compiler)) // app.use(hotDevMiddleware(compiler))
} // }
require('./utils/scanner')(); require('./utils/scanner')();

View File

@ -1,56 +1,18 @@
const data = require('./data.json'); import data from './data.json'
const api = require('express').Router();
const fs = require('fs');
const path = require('path');
const config = require('../../config.json');
api.get('/blog', (req, res) => { export function getData(path = ''){
res.set('Cache-Control', 'no-cache'); if (path === ''){
data.posts.sort((a,b) => { return data
return new Date(b.published) - new Date(a.published);
})
res.json(data.posts);
});
api.get('/about', (req, res) => {
const renderPath = path.join(process.cwd(), '/renders', 'about.html');
res.set('Cache-Control', 'max-age=86400');
fs.readFile(renderPath, 'utf8', (err, data) => {
if (err) {
res.json({
error: 404
});
} else { } else {
res.json({ fileName = '../../content/' + path
body: data, return readFile(fileName)
}
}
function readFile(fileName, type) {
return new Promise(function(resolve, reject){
fs.readFile(fileName, (err, data) => {
err ? reject(err) : resolve(data);
});
}); });
} }
});
});
api.get('/post/:postname', (req, res) => {
res.set('Cache-Control', 'no-cache');
const postname = req.params.postname;
const post = data.posts.find((el) => {
return el.filename === postname
});
const renderPath = path.join(process.cwd(), '/renders', postname + '.html');
fs.readFile(renderPath, 'utf8', (err, data) => {
if (err) {
res.json({
error: 404
});
} else {
res.json({
published: post.published,
link: post.link,
title: post.title,
body: data,
});
}
});
});
module.exports = api;

View File

@ -17,9 +17,6 @@ const routes = [
getData: (path = '') => getData( getData: (path = '') => getData(
path.split('/').pop() path.split('/').pop()
) )
},
{
component: NotFoundWrapper,
} }
] ]

View File

@ -10,6 +10,17 @@ function serverRender(req, res) {
const activeRoute = routes.find((route) => matchPath(req.url, route)) || {} const activeRoute = routes.find((route) => matchPath(req.url, route)) || {}
const promise = activeRoute.fetchInitialData
? activeRoute.fetchInitialData(req.path)
: Promise.resolve()
promise.then((data) => {
const markup = renderToString(
<Router location={req.url} context={context}>
<App />
</Router>,
);
})
let markup = ''; let markup = '';
let status = 200; let status = 200;

View File

@ -1,23 +1,14 @@
const { resolve, join } = require('path') const { resolve, join } = require('path')
const webpack = require('webpack') const webpack = require('webpack')
const ManifestPlugin = require('webpack-manifest-plugin'); const UglifyJsPlugin = require("uglifyjs-webpack-plugin")
const MiniCssExtractPlugin = require("mini-css-extract-plugin")
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin")
const CompressionPlugin = require("compression-webpack-plugin")
const ManifestPlugin = require('webpack-manifest-plugin')
const CleanWebpackPlugin = require('clean-webpack-plugin')
const nodeExternals = require('webpack-node-externals')
const config = { const commonConfig = {
mode: 'development',
devtool: 'cheap-eval-source-map',
context: resolve(__dirname, 'src'),
entry: {
bundle: [
'webpack-hot-middleware/client',
'./app-client.js'
]
},
output: {
path: resolve(__dirname,'public/static'),
filename: 'bundle.js',
publicPath: '/static/'
},
module: {
rules: [ rules: [
{ {
test: /\.js$/, test: /\.js$/,
@ -29,9 +20,7 @@ const config = {
{ {
test: /\.scss$/, test: /\.scss$/,
use: [ use: [
{ MiniCssExtractPlugin.loader,
loader: "style-loader"
},
{ {
loader: 'css-loader', loader: 'css-loader',
options: { options: {
@ -44,31 +33,70 @@ const config = {
loader: "postcss-loader" loader: "postcss-loader"
}, },
{ {
loader: "sass-loader" loader: 'sass-loader'
} }
] ]
}, },
{ {
test: /\.(png|jpg)$/, test: /\.(png|jpg)$/,
exclude: /node_modules/, exclude: /node_modules/,
loader: 'url-loader' loader: 'url-loader',
},
{
test: /\.(html)$/,
use: {
loader: 'html-loader',
options: { options: {
attrs: [':data-src'] limit: 8192
}
} }
}, },
] ]
}
const browserConfig = {
mode: 'production',
context: resolve(__dirname, 'src'),
entry: {
bundle: [
'./app-client.js'
]
},
output: {
path: resolve(__dirname, 'public/static'),
filename: '[name].[contenthash].js',
publicPath: '/static/'
},
module: commonConfig,
optimization: {
minimizer: [
new UglifyJsPlugin({
cache: true,
parallel: true,
sourceMap: true // set to true if you want JS source maps
}),
new OptimizeCSSAssetsPlugin({})
]
}, },
plugins: [ plugins: [
new webpack.HotModuleReplacementPlugin(), new webpack.DefinePlugin({__isBrowser__: "true"}),
new webpack.NoEmitOnErrorsPlugin(), new CleanWebpackPlugin(['dist', 'public/static'], {}),
new webpack.NamedModulesPlugin(), new MiniCssExtractPlugin({filename: '[name].[contenthash].css'}),
new ManifestPlugin({'writeToFileEmit': true}), new CompressionPlugin({}),
new ManifestPlugin(),
] ]
} }
module.exports = config
const serverConfig = {
entry: './src/server.js',
target: 'node',
externals: [nodeExternals()],
output: {
path: __dirname,
filename: 'server.js',
publicPath: '/'
},
module: commonConfig,
plugins: [
new webpack.DefinePlugin({
__isBrowser__: "false"
}),
new MiniCssExtractPlugin({filename: '[name].[contenthash].css'}),
]
}
module.exports = [browserConfig, serverConfig]

View File

@ -1,80 +0,0 @@
const { resolve, join } = require('path')
const webpack = require('webpack')
const UglifyJsPlugin = require("uglifyjs-webpack-plugin")
const MiniCssExtractPlugin = require("mini-css-extract-plugin")
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin")
const CompressionPlugin = require("compression-webpack-plugin")
const ManifestPlugin = require('webpack-manifest-plugin')
const CleanWebpackPlugin = require('clean-webpack-plugin')
const config = {
mode: 'production',
context: resolve(__dirname, 'src'),
entry: {
bundle: [
'./app-client.js'
]
},
output: {
path: resolve(__dirname, 'public/static'),
filename: '[name].[contenthash].js',
publicPath: '/static/'
},
module: {
rules: [
{
test: /\.js$/,
use: [
'babel-loader'
],
exclude: '/node_modules/'
},
{
test: /\.scss$/,
use: [
MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
options: {
modules: true,
importLoaders: 2,
localIdentName: '[name]__[local]___[hash:base64:5]'
}
},
{
loader: "postcss-loader"
},
{
loader: 'sass-loader'
}
]
},
{
test: /\.(png|jpg)$/,
exclude: /node_modules/,
loader: 'url-loader',
options: {
limit: 8192
}
},
]
},
optimization: {
minimizer: [
new UglifyJsPlugin({
cache: true,
parallel: true,
sourceMap: true // set to true if you want JS source maps
}),
new OptimizeCSSAssetsPlugin({})
]
},
plugins: [
new CleanWebpackPlugin(['dist', 'public/static'], {}),
new MiniCssExtractPlugin({filename: '[name].[contenthash].css'}),
new CompressionPlugin({}),
new ManifestPlugin(),
]
}
module.exports = config

View File

@ -6735,6 +6735,11 @@ webpack-manifest-plugin@^2.0.3:
lodash ">=3.5 <5" lodash ">=3.5 <5"
tapable "^1.0.0" tapable "^1.0.0"
webpack-node-externals@^1.7.2:
version "1.7.2"
resolved "https://registry.yarnpkg.com/webpack-node-externals/-/webpack-node-externals-1.7.2.tgz#6e1ee79ac67c070402ba700ef033a9b8d52ac4e3"
integrity sha512-ajerHZ+BJKeCLviLUUmnyd5B4RavLF76uv3cs6KNuO8W+HuQaEs0y0L7o40NQxdPy5w0pcv8Ew7yPUAQG0UdCg==
webpack-sources@^1.0.1, webpack-sources@^1.1.0: webpack-sources@^1.0.1, webpack-sources@^1.1.0:
version "1.1.0" version "1.1.0"
resolved "https://registry.yarnpkg.com/webpack-sources/-/webpack-sources-1.1.0.tgz#a101ebae59d6507354d71d8013950a3a8b7a5a54" resolved "https://registry.yarnpkg.com/webpack-sources/-/webpack-sources-1.1.0.tgz#a101ebae59d6507354d71d8013950a3a8b7a5a54"