I´m trying to understand how to use webpack-dev-server for hot bundling and reloading and I got the following code from react-redux-universal-hot-example:
var Express = require('express');
var webpack = require('webpack');
var config = require('../src/config');
var webpackConfig = require('./dev.config');
var compiler = webpack(webpackConfig);
var host = config.host || 'localhost';
var port = (Number(config.port) + 1) || 3001;
var serverOptions = {
contentBase: 'http://' + host + ':' + port,
quiet: true,
noInfo: true,
hot: true,
inline: true,
lazy: false,
publicPath: webpackConfig.output.publicPath,
headers: {'Access-Control-Allow-Origin': '*'},
stats: {colors: true}
};
var app = new Express();
app.use(require('webpack-dev-middleware')(compiler, serverOptions));
app.use(require('webpack-hot-middleware')(compiler));
app.listen(port, function onAppListening(err) {
if (err) {
console.error(err);
} else {
console.info('==> Webpack development server listening on port %s', port);
}
});
Questions:
a) Why is this code calling var app = Express() to seutp an express server ? Isn´t it webpack-dev-server a server itself ?
b) From the webpack-dev-server I expected somthing like:
var WebpackDevServer = require("webpack-dev-server");
var webpack = require("webpack");
var fs = require("fs");
var compiler = webpack({
// configuration
});
var server = new WebpackDevServer(compiler, {
// webpack-dev-server options
}) ;
Why is react-redux-universal-hot-example doing it inside a new instance of express() ?
c) Is there any docs or tutorials of this type of webpack-dev-server usage ?
Thanks for helping - I´m confused here.
As far as you see your application require a pair of middlewares
app.use(require('webpack-dev-middleware')(compiler, serverOptions));
app.use(require('webpack-hot-middleware')(compiler));
It's just easier to set it up having express middleware system.
There is a good documentation with examples https://webpack.github.io/docs/webpack-dev-server.html
Related
My api has stopped working, previously it worked fine and as far as i am aware I have changed nothing. When i tested my endpoint i received an internal server error.
Here is a link to my hosted api https://frozen-scrubland-34339.herokuapp.com/api
I have just checked some of my other apis and none are working either, same message. it appears my code isnt the issue but postgres itself?
Any help on what to do would be appreciated
When i tried to npm run prod to re-push it to heroku i received: 'Error: The server does not support SSL connections'
Again this was never an issue previously when it worked.
I imagine i have changed something with heroku itself by accident?
app.js
const express = require("express");
const app = express();
const apiRouter = require("./routers/api-router");
const cors = require("cors");
const {
handle404s,
handlePSQLErrors,
handleCustomError,
} = require("./controllers/errorHandling");
app.use(cors());
app.use(express.json());
app.use("/api", apiRouter);
app.use("*", handle404s);
app.use(handlePSQLErrors);
app.use(handleCustomError);
module.exports = app;
connection.js
const { DB_URL } = process.env;
const ENV = process.env.NODE_ENV || "development";
const baseConfig = {
client: "pg",
migrations: {
directory: "./db/migrations",
},
seeds: {
directory: "./db/seeds",
},
};
const customConfigs = {
development: { connection: { database: "away_days" } },
test: { connection: { database: "away_days_test" } },
production: {
connection: {
connectionString: DB_URL,
ssl: {
rejectUnauthorized: false,
},
},
},
};
module.exports = { ...baseConfig, ...customConfigs[ENV] };
There are 3 file created in /config.
default.json
{
"host": "localhost",
"port": "PORT",
"msg": "default"
}
local.json
{
"host": "localhost",
"port": 3030,
"msg": "local"
}
dev.json
{
"host": "localhost",
"port": 3030,
"msg": "dev"
}
Whenever the application runs, it should log something like info: Feathers application started on http://localhost:3030 in dev, which "dev" is the msg variable in config file.
index.js
/* eslint-disable no-console */
const logger = require('./logger');
const app = require('./app');
const port = app.get('port');
const msg = app.get('msg');
const server = app.listen(port);
process.on('unhandledRejection', (reason, p) =>
logger.error('Unhandled Rejection at: Promise ', p, reason)
);
server.on('listening', () =>
logger.info('Feathers application started on http://%s:%d in %s', app.get('host'), port, msg)
);
I tried to set NODE_ENV=dev, but every time I run the application by nodemon --legacy-watch ./src, it shows:
info: Feathers application started on http://localhost:3030 in local
but I am expecting
info: Feathers application started on http://localhost:3030 in dev
I tried to log process.env.NODE_ENV, but it shows dev correctly
app.js
const path = require('path');
const favicon = require('serve-favicon');
const compress = require('compression');
const helmet = require('helmet');
const cors = require('cors');
const logger = require('./logger');
const feathers = require('#feathersjs/feathers');
process.env['NODE_CONFIG_DIR'] = 'config/'. // I tried to add this according to doc but still not working
const configuration = require('#feathersjs/configuration');
const express = require('#feathersjs/express');
const socketio = require('#feathersjs/socketio');
const middleware = require('./middleware');
const services = require('./services');
const appHooks = require('./app.hooks');
const channels = require('./channels');
const authentication = require('./authentication');
const sequelize = require('./sequelize');
const app = express(feathers());
// Load app configuration
app.configure(configuration());
console.log(app.settings.msg); //<--------------------------------- show "local"
console.log(process.env.NODE_ENV); // <---------------------------- show "dev"
// Enable security, CORS, compression, favicon and body parsing
app.use(helmet({
contentSecurityPolicy: false
}));
app.use(cors());
app.use(compress());
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ limit: '10mb', extended: true }));
app.use(favicon(path.join(app.get('public'), 'favicon.ico')));
// Host the public folder
app.use('/', express.static(app.get('public')));
// Set up Plugins and providers
app.configure(express.rest());
app.configure(socketio());
app.configure(sequelize);
// Configure other middleware (see `middleware/index.js`)
app.configure(middleware);
app.configure(authentication);
// Set up our services (see `services/index.js`)
app.configure(services);
// Set up event channels (see channels.js)
app.configure(channels);
// Configure a middleware for 404s and the error handler
app.use(express.notFound());
app.use(express.errorHandler({ logger }));
app.hooks(appHooks);
module.exports = app;
Update
After I remove local.json, it works perfectly but it doesn't makes sense?
Trying to init browsersync with https, http2 and gzip, but can never seem to get them all to play nicely together
var gulp = require('gulp');
var browserSync = require('browser-sync');
var compression = require('compression');
gulp.task('browser-sync', function() {
browserSync.init({
server: {
baseDir: "dist",
middleware: [compression()]
},
httpModule: 'http2',
https: {
key: "/path/to/localhost.key",
cert: "/path/to/localhost.crt"
}
})
})
I can get http2 to work without compression, and compression to work without http2, but never both at the same time... The error I get is
Error: Can't set headers after they are sent.
Doing the same thing using express was successful
var express = require('express');
var http2 = require('spdy');
var serveStatic = require('serve-static');
var compression = require('compression');
var credentials = {
key: "/path/to/localhost.key",
cert: "/path/to/localhost.crt"
};
var app = express();
app.use(compression())
app.use(serveStatic('./dist', {
'extensions': ['html'],
'maxAge': 3600000
}))
var httpsServer = http2.createServer(credentials, app);
httpsServer.listen(8888);
But no joy using browsersync
Any help, much appreciated.
I'm trying to set up a very simple script that fetch's data from an API and consumes it's data. I need to use CORS, so I set up a node/express server and pointed it to my Webpack bundle. The error I am getting is global is not defined. From googling this I've seen people fix their problems by disabling react/redux tools which seemed to point at hot reloading. Problem is, I'm not using hot reloading.
After seeing that I looked into what I am using global which pointed at my fetch expression. However, removing all my fetch code didn't solve anything
My server looks like this
const express = require('express');
const bodyParser = require('body-parser');
const path = require('path');
const app = express();
const cors = require('cors');
const port = process.env.PORT || 3000;
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(cors());
app.use(express.static(path.join(__dirname, '../dist')));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, '../index.html'));
});
app.listen(port, function(){
console.log('server running on http://127.0.0.1:' + port + '/');
});
and my webpack config looks like this
var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: ['babel-polyfill', './scripts/app.js'],
target: "node",
output: { path: __dirname, filename: './dist/bundle.js' },
devtool: 'source-map',
module: {
loaders: [
{
test: /.js?$/,
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ['es2015'],
"plugins": ["transform-object-rest-spread"]
}
}
]
}
};
All i can think of now is that I didn't set up my express server correctly or I'm missing something in my webpack config.
Alright, The issue was being caused by placing babel-polyfill in my entry point in my webpack.config. As I already had a preset for ES2015 I didn't need the polyfill.
I am unsure as to why I had placed the babel-polyfill in my entry.
I have a gulpfile, where I create a webpackDevServer to live-update my js code. I set a process.env.NODE_ENV variable in gulpfile, but for some reason webpack doesn't see it - it is undefined.
Here's the relevant piece of my gulpfile.js:
gulp.task("watch", ["_set-env:dev"], function() {
// modify default webpack configuration for Development Server
var webpackDevConfig = Object.create(webpackConfig);
webpackDevConfig.devtool = "eval";
webpackDevConfig.debug = "true";
new webpackDevServer(webpack(webpackDevConfig), {
proxy: {
"/api/*": {target: "http://localhost:8000", secure: false},
"/static/*": {target: "http://localhost:8000", secure: false},
"/media/*": {target: "http://localhost:8000", secure: false}
}
}).listen(8001, "localhost", function (err) {
if (err) throw new gutil.PluginError("webpack-dev-server", err);
gutil.log("[webpack-dev-server]", "http://localhost:8001" + webpackDevConfig.output.publicPath);
});
});
gulp.task("_set-env:dev", function() {
gutil.log("set-env", "ENV => development");
genv({
vars: {
NODE_ENV: "development"
}
});
});
Then in webpack I check its value and it is undefined:
const webpack = require("webpack");
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
...
const environmentsFile = path.join(__dirname, "/environments.json");
const nodeModulesPath = path.join(__dirname, "/node_modules");
const bowerComponentsPath = path.join(__dirname, "/bower_components");
console.log("!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!");
console.log(process.env.NODE_ENV);
const webpackConfig = {
entry: {
app: ["app.js"]
},
And on the console I see:
$ gulp watch
!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
undefined
[22:28:34] Using gulpfile ~/Documents/frontend/gulpfile.js
[22:28:34] Starting '_set-env:dev'...
[22:28:34] set-env ENV => development
[22:28:34] Finished '_set-env:dev' after 7.63 ms
[22:28:34] Starting 'watch'...
You probably have something like this close to the top of your gulpfile:
var webpackConfig = require('./webpack.config.js');
That means your webpack configuration is evaluated before the _set-env:dev task even runs. Remember: your gulpfile only defines tasks. The tasks themselves aren't run until after the entire gulpfile has been evaluated.
You need to defer requiring your webpack configuration until after the _set-env:dev task has run by deleting the line at the top of your gulpfile and putting the require() directly into your watch task:
gulp.task("watch", ["_set-env:dev"], function() {
// modify default webpack configuration for Development Server
var webpackDevConfig = Object.create(require('./webpack.config.js'));