WDS Disconnected! sockjs-node refused, webpack-dev-middleware, expressjs - reactjs

Some sockjs-node errors here
I'm building a dev server using express...
ADDED webpack-dev-middleware and webpack-hot-middleware for my React
Here's my webpack.config.js:
// require('dotenv').config()
const ESLintPlugin = require('eslint-webpack-plugin')
const ErrorOverlayPlugin = require('error-overlay-webpack-plugin')
const HTMLWebpackPlugin = require('html-webpack-plugin')
const { WebpackManifestPlugin } = require('webpack-manifest-plugin')
const path = require('path')
const webpack = require('webpack');
const eslintPlugin = new ESLintPlugin({ fix: true })
const manifestPlugin = new WebpackManifestPlugin()
const HMRPlugin = new webpack.HotModuleReplacementPlugin()
const htmlPlugin = new HTMLWebpackPlugin({
template: path.resolve(__dirname, 'build/app.html'),
filename: 'index.html',
})
const errorPlugin = new ErrorOverlayPlugin()
module.exports = {
mode: 'development',
entry: [
'webpack-dev-server/client?http://127.0.0.1:3999/',
'webpack/hot/only-dev-server',
'./src/index.js',
],
output: {
path: path.resolve(__dirname, 'build'),
filename: 'main.bundle.js',
publicPath: '/',
pathinfo: true,
},
devServer: {
socket: 'socket',
hot: true,
overlay: true,
port: 3999,
inline: true,
stats: 'normal',
historyApiFallback: true,
},
performance: {
hints: false,
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
include: path.resolve(__dirname, 'src'),
exclude: /node_modules/,
use: ['babel-loader'],
},
{
test: /\.(scss)$/,
use: ['style-loader', 'css-loader', 'sass-loader'],
},
{
test: /\.(png|svg|jpe?g|gif|ico)$/i,
type: 'asset/resource',
},
{
test: /\.(woff|woff2|eot|ttf|otf)$/i,
type: 'asset/resource',
},
],
},
plugins: [eslintPlugin, manifestPlugin, errorPlugin, htmlPlugin, HMRPlugin],
devtool: 'cheap-module-source-map',
}
My server.js:
import express from 'express'
import debug from 'debug'
import logger from 'morgan'
import chalk from 'chalk'
import dotenv from 'dotenv'
import webpack from 'webpack'
import hotMiddleware from 'webpack-hot-middleware'
import wpDevMiddleware from 'webpack-dev-middleware'
import cors from 'cors'
import wpConf from './webpack.config'
dotenv.config()
const app = express()
const port = process.env.PORT
const ecoS = debug('ECO-Server')
const ecoC = debug('ECO-Client')
const compiler = webpack(wpConf)
const skipLog = (req, res) => {
var { url } = req
if (url.match(/sockjs/gi)) {
return true
}
return false
}
app.set('port', port)
app.use(cors({ maxAge: 1000 * 60 * 60 * 24 * 2 }))
app.use(
logger('dev', {
stream: {
write: msg => ecoC(msg.trimEnd()),
},
skip: skipLog,
})
)
app.use(wpDevMiddleware(compiler))
app.use(hotMiddleware(compiler))
setTimeout(() => {
app.listen(port, () => ecoS('Listening on port', chalk.cyanBright(port)))
}, 4000)
127.0.0.1:3999/sockjs-node/info?t=1615910198493:1 Failed to load resource: net::ERR_CONNECTION_REFUSED
sockjs.js:1609 XHR failed loading: GET "http://127.0.0.1:3999/sockjs-node/info?t=1615910266231".
please help me this... anyone?

Related

Webpack react compiles even when there is error in the code

I am using webpack 5 I will put the content of my config below, the issue I am facing is that the code is getting compiled even if I tried making a function call in the code and that function doesn't exist but the code compiles and the app doesn't give any sort of error and of course the functionality isn't working which is expected.
My config file
const path = require("path");
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const UglifyJsPlugin = require("uglifyjs-webpack-plugin");
const OptimizeCssAssetsPlugin = require("optimize-css-assets-webpack-plugin");
const DotenvWebpackPlugin = require("dotenv-webpack");
const mode = process.env.NODE_ENV
const IS_PROD = mode === 'production';
const IS_DEV = !IS_PROD;
const ROOT_DIR = path.resolve(__dirname, '../');
const SRC_DIR = path.resolve(ROOT_DIR, 'src');
module.exports = {
mode,
entry: "./src/index.js",
devServer: {
historyApiFallback: true,
compress: true,
port: 3000,
client: {
overlay: true,
}
},
output: {
publicPath: "/",
path: path.resolve(__dirname, "dist"),
filename: "bundle.js",
},
optimization: {
minimizer: [
new UglifyJsPlugin({
cache: true,
parallel: true,
sourceMap: true // set to true if you want JS source maps for css
}),
new OptimizeCssAssetsPlugin({})
]
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
options: {
//cacheDirectory: true,
//cacheCompression: false,
envName: IS_PROD ? "production" : "development"
}
}
},
{
test: /\.(css)$/,
use: [
IS_PROD ? MiniCssExtractPlugin.loader : "style-loader",
"css-loader"
]
},
{
test: /\.(png|gif|jpg|svg|ttf|eot|svg|otf|woff(2)?)(\?[a-z0-9]+)?$/,
type: 'asset/resource'
}
]
},
resolve: {
extensions: ['.js', '.jsx'],
},
plugins: [
new DotenvWebpackPlugin({
path: path.resolve(__dirname, '.env'),
systemvars: true
}),
new HtmlWebpackPlugin({
template: path.resolve(__dirname, 'public/index.html'),
}),
new webpack.HotModuleReplacementPlugin(),
new MiniCssExtractPlugin({
experimentalUseImportModule: true,
filename: "assets/css/[name].[contenthash:8].css",
chunkFilename: "assets/css/[name].[contenthash:8].chunk.css"
})
],
}
Code snippet
if (data.role === "REGISTERED") {
showMessageWrong("Your access request is yet to be approved by your manager!") // there is no such function the actual function is showMessage
//redirectToLogin()
}
This causes lot of issue when debugging the app won't work but find RC will be troublesome can someone point out what am I missing!

React errors showing in console but not window

When I work with a CRA app, and most React Apps, an error in the code will cause the browser to show an error screen instead of the application.
The legacy code I'm working on doesn't do this. An error that basically crashes the app just shows a blank screen (black screen, which I imagine is our background color), and you only know what's going on by opening the dev console for the browser.
The project was made with CRA, but quite a while ago. It does not include react-scripts anywhere.
How do I set this back to "normal" so that the errors will show in the browser window itself?
This is my current webpack config
const os = require('os');
const path = require('path');
const ip = require('my-local-ip');
const colors = require('colors');
const process = require('process');
const webpack = require('webpack');
const states = require('./util/state-spoof');
const childProcess = require('child_process');
const PlayerIdPlugin = require('./plugins/PlayerIdPlugin');
const eslintFormatter = require('react-dev-utils/eslintFormatter');
const MiniCssExtractPlugin = require('extract-css-chunks-webpack-plugin');
const envPort = process.env.PORT;
const port = envPort ? envPort : 3000;
const spoof = states[process.env.SPOOF || 'NH'];
const forcedProdAPI = process.env.FORCE_PROD_API || false;
const platform = os.platform().toLowerCase();
const isLinux = platform === 'linux';
const isWindows = platform === 'win32' || platform === 'win64';
if (!process.env.NODE_ENV) process.env.NODE_ENV = 'development';
const mode = process.env.NODE_ENV;
const sessionKey = process.env.SESSION_KEY || '';
const linter = {
test: /\.(js|jsx|mjs)$/,
enforce: 'pre',
use: [
{
options: {
formatter: eslintFormatter,
eslintPath: require.resolve('eslint'),
},
loader: require.resolve('eslint-loader'),
},
],
include: path.resolve(__dirname, 'src'),
};
const imgLoad = {
test: /\.(gif|png|jpe?g)$/i,
loader: require.resolve('url-loader'),
options: {
limit: 10000,
name: 'static/media/[name].[hash:8].[ext]',
},
};
const jsLoad = {
test: /\.(js|jsx|mjs)$/,
loader: require.resolve('babel-loader'),
options: {
cacheDirectory: true,
},
exclude: /(node_modules)/,
};
const tsLoad = {
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
};
const sassLoad = {
test: /\.s?(a|c)ss$/,
use: [
mode.includes('dev') ? 'style-loader' : MiniCssExtractPlugin.loader,
{
loader: 'css-loader',
},
{
loader: 'sass-loader',
},
],
};
const fileLoad = {
exclude: [/\.(js|jsx|mjs)$/, /\.html$/, /\.json$/],
loader: require.resolve('file-loader'),
options: {
name: 'static/media/[name].[hash:8].[ext]',
},
};
module.exports = {
mode: mode,
stats: 'errors-only',
entry: './src/browser/index.js',
output: {
path: path.resolve(__dirname, '..', 'src', 'public'),
filename: 'static/scripts/bundle.js',
publicPath: '/',
},
module: {
rules: [
linter,
{ oneOf: [imgLoad, jsLoad, tsLoad, sassLoad, fileLoad] },
],
},
plugins: [
new PlayerIdPlugin({
output: path.resolve(
__dirname, '..', 'src', 'browser', 'services', 'PlayerIDHelper.js'
),
}),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(mode),
'process.env.FORCE_PROD_API': JSON.stringify(forcedProdAPI),
'process.env.SESSION_KEY': JSON.stringify(sessionKey),
'process.env.NERF_THIRD_PARTY': 'false',
'process.env.BROWSER': 'true',
'process.env.SPOOF': JSON.stringify(spoof),
}),
new MiniCssExtractPlugin({
filename: 'static/styles/main.css',
}),
new webpack.HotModuleReplacementPlugin(),
],
devtool: 'inline-source-map',
devServer: {
hot: true,
host: '0.0.0.0',
port: port,
disableHostCheck: true,
quiet: true,
compress: true,
contentBase: path.resolve(__dirname, '..', 'src', 'public'),
historyApiFallback: true,
before: () => {
console.log(
colors.bold.white(
`Server currently listening :\n`
) +
colors.reset.yellow(
`\nMachine access: http://localhost:${port}\n`
) +
colors.reset.yellow(
`Network access: http://${ip()}:${port}`
)
);
if (!isLinux && !isWindows) {
childProcess.execSync('ps cax | grep "Google Chrome"');
childProcess.execSync(
`osascript chrome.applescript "${encodeURI(
`http://localhost:${port}`
)}"`,
{
cwd: path.resolve(__dirname),
stdio: 'ignore',
}
);
}
},
},
};

On starting Styleguidedist server it fails with Module parse failed: Unexpected token

Im trying to start my style guide server but it keeps throwing following error:
I believe this occurs when the babel loaders are not configured for jsx files. But this isnt true as I am able to start my project without errors. But when I try to start the style guide I end up with this.
Here is my styleguide config file
module.exports = {
title: 'Component Library',
webpackConfig: Object.assign(
{},
require("./config/webpack/webpack.dev.config.js"),
{
/* Custom config options if required */
}
),
components: "source/components/**/*.jsx",
template: {
head: {
links: [
{
rel: "stylesheet",
href:
"https://fonts.googleapis.com/css?family=Poppins:400,400i,600,600i,700,700i&display=swap"
}
]
}
},
theme: {
fontFamily: {
base: '"Poppins", sans-serif'
}
},
styles: function styles(theme) {
return {
Playground: {
preview: {
backgroundColor: '#29292e'
},
},
Code: {
code: {
fontSize: 14,
},
},
};
},
};
Here is my webpack config
var webpack = require('webpack');
var path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const { CleanWebpackPlugin } = require('clean-webpack-plugin');
// const InterpolateHtmlPlugin = require('interpolate-html-plugin');
const WebpackAssetsManifest = require('webpack-manifest-plugin');
const CopyPlugin = require('copy-webpack-plugin');
const ProgressBarPlugin = require('progress-bar-webpack-plugin');
const reactLoadablePlugin = require('react-loadable/webpack')
.ReactLoadablePlugin;
const workboxPlugin = require('workbox-webpack-plugin');
module.exports = (env) => ({
mode: 'development',
entry: path.join(__dirname, '../../index.js'),
output: {
filename: '[name].bundle.[hash].js',
chunkFilename: '[name].bundle.[hash].js',
path: path.join(__dirname, '../../../build'),
publicPath: '/'
},
optimization: {
splitChunks: {
cacheGroups: {
commons: {
test: /[\\/]node_modules[\\/]/,
// cacheGroupKey here is `commons` as the key of the cacheGroup
name(module, chunks, cacheGroupKey) {
const moduleFileName = module
.identifier()
.split('/')
.reduceRight(item => item);
const allChunksNames = chunks.map(item => item.name).join('~');
return `${cacheGroupKey}-${allChunksNames}-${moduleFileName}`;
},
chunks: 'all'
}
}
}
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: path.resolve(__dirname, 'node_modules'),
loader: 'babel-loader'
},
{
test: /\.svg(\?.*)?$/, // match img.svg and img.svg?param=value
use: [
'url-loader', // or file-loader or svg-url-loader
'svg-transform-loader'
]
},
{
test: /\.png(\?.*)?$/, // match img.svg and img.svg?param=value
use: [
'url-loader', // or file-loader or svg-url-loader
]
},
{
test: /\.less$/,
use: [
'style-loader',
'css-loader',
{
loader: 'less-loader',
options: {
javascriptEnabled: true
}
}
]
},
{
test: /\.(sa|sc|c)ss$/,
exclude: path.resolve(__dirname, 'node_modules'),
use: [
'style-loader',
MiniCssExtractPlugin.loader,
'css-loader',
'postcss-loader',
'sass-loader'
]
}
]
},
resolve: {
extensions: ['.js', '.jsx']
},
plugins: [
new webpack.EnvironmentPlugin({
APP_ENVIRONMENT: process.env.APP_ENVIRONMENT,
API_KEY: process.env.API_KEY,
AUTH_DOMAIN: process.AUTH_DOMAIN,
DB_URL: process.env.DB_URL,
PROJECT_ID: process.env.PROJECT_ID
}),
new CleanWebpackPlugin({
path: path.join(__dirname, '../../../build')
}),
new WebpackAssetsManifest({
fileName: 'asset-manifest.json'
}),
new HtmlWebpackPlugin({
title: '<<app>>',
template: 'main.html',
minify: {
collapseWhitespace: false,
removeComments: true,
useShortDoctype: false
}
}),
new MiniCssExtractPlugin({
filename: 'style.[contenthash].css'
}),
new CopyPlugin([
{
from: 'public',
to: 'public'
}
]),
new ProgressBarPlugin({
format: ' build [:bar] ' + ':percent' + ' (:elapsed seconds)' + ' :msg'
}),
new reactLoadablePlugin({
filename: './react-loadable.json'
}),
new workboxPlugin.InjectManifest({
swSrc: path.join(__dirname, '../../public/service-worker.js')
})
],
devServer: {
contentBase: path.join(__dirname, '/'),
filename: 'main.html',
compress: true,
port: 3000,
historyApiFallback: true,
disableHostCheck: true,
useLocalIp: true,
host: '0.0.0.0'
},
devtool: 'eval-source-map'
});
The problem was with the webpack file I was exporting the webpack configurations as a function.
Earlier:
module.exports = (env) => ({
....your webpack configurations
})
Instead of exporting everything as a function I exported it as
Now:
module.exports = {
....your webpack configurations
}
But can someone tell me why the earlier implementation didnt work?

deploying officejs fabric react word add in

I have a word add in written in typescript using Officejs and office-ui-fabric-react. Everything works fine with the server running locally. I'd like to deploy into AWS S3 with Cloudfront. I'm building with npm run build, and npm run deploy (using deploy command "aws --profile profile-name s3 sync dist/ s3://bucketname". Static web site hosting is enabled in the S3 bucket. All files from the dist directory are seen in the bucket. After inserting the add in into Word with a manifest.xml file that points to the cloudfront endpoint I'm getting the error "Uncaught ReferenceError: React is not defined". The same error occurs when I point directly to the S3 static web endpoint. To see if I've missed anything I deployed a generic create-react-app using the steps above and it runs fine. I'm assuming that the problem lies with my webpack config so I've included that here (common, and prod). I'd be happy to include anything else that's needed. I'm also open to other deployment options if using AWS is causing the problem.
webpack.common.js:
const webpack = require('webpack');
const path = require('path');
const package = require('../package.json');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const autoprefixer = require('autoprefixer');
const build = (() => {
const timestamp = new Date().getTime();
return {
name: package.name,
version: package.version,
timestamp: timestamp,
author: package.author
};
})();
const entry = {
vendor: [
'react',
'react-dom',
'core-js',
'office-ui-fabric-react'
],
app: [
'react-hot-loader/patch',
'./index.tsx',
],
'function-file': '../function-file/function-file.ts'
};
const rules = [
{
test: /\.tsx?$/,
use: [
'react-hot-loader/webpack',
'ts-loader'
],
exclude: /node_modules/
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
},
{
test: /\.less$/,
use: ['style-loader', 'css-loader', 'less-loader']
},
{
test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
use: {
loader: 'file-loader',
query: {
name: 'assets/[name].[ext]'
}
}
}
];
const output = {
path: path.resolve('dist'),
publicPath: '/',
filename: '[name].[hash].js',
chunkFilename: '[id].[hash].chunk.js'
};
const WEBPACK_PLUGINS = [
new webpack.NamedModulesPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new webpack.BannerPlugin({ banner: `${build.name} v.${build.version} (${build.timestamp}) © ${build.author}` }),
new webpack.DefinePlugin({
ENVIRONMENT: JSON.stringify({
build: build
})
}),
new webpack.LoaderOptionsPlugin({
options: {
postcss: [
autoprefixer({ browsers: ['Safari >= 8', 'last 2 versions'] }),
],
htmlLoader: {
minimize: true
}
}
})
];
module.exports = {
context: path.resolve('./src'),
entry,
output,
resolve: {
extensions: ['.js', '.jsx', '.ts', '.tsx', '.scss', '.css', '.html']
},
module: {
rules,
},
optimization: {
splitChunks: {
chunks: 'async',
minChunks: Infinity,
name: 'vendor'
}
},
plugins: [
...WEBPACK_PLUGINS,
new ExtractTextPlugin('[name].[hash].css'),
new HtmlWebpackPlugin({
title: 'letterConfig',
filename: 'index.html',
template: './index.html',
chunks: ['app', 'vendor', 'polyfills']
}),
new HtmlWebpackPlugin({
title: 'letterConfig',
filename: 'function-file/function-file.html',
template: '../function-file/function-file.html',
chunks: ['function-file']
}),
new CopyWebpackPlugin([
{
from: '../assets',
ignore: ['*.scss'],
to: 'assets',
}
])
]
};
webpack.prod.js:
const webpack = require('webpack');
const webpackMerge = require('webpack-merge');
const commonConfig = require('./webpack.common.js');
const ENV = process.env.NODE_ENV = process.env.ENV = 'development';
module.exports = webpackMerge(commonConfig, {
devtool: 'source-map',
externals: {
'react': 'React',
'react-dom': 'ReactDOM'
},
performance: {
hints: "warning"
},
optimization: {
minimize: true
}
});
index.tsx:
import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { AppContainer } from 'react-hot-loader';
import { initializeIcons } from 'office-ui-fabric-react/lib/Icons';
import App from './components/App';
import './styles.less';
import 'office-ui-fabric-react/dist/css/fabric.min.css';
initializeIcons();
let isOfficeInitialized = false;
const title = 'letterConfig';
const render = (Component) => {
ReactDOM.render(
<AppContainer>
<Component title={title} isOfficeInitialized={isOfficeInitialized} />
</AppContainer>,
document.getElementById('container')
);
};
/* Render application after Office initializes */
Office.initialize = () => {
console.log('init');
isOfficeInitialized = true;
render(App);
};
/* Initial render showing a progress bar */
render(App);
if ((module as any).hot) {
(module as any).hot.accept('./components/App', () => {
const NextApp = require('./components/App').default;
render(NextApp);
});
}
It turned out that it was looking for a globally defined "React", and so not resolving via an npm module. In the webpack.prod.js file removing the following solved the problem:
externals: {
'react': 'React',
'react-dom': 'ReactDOM'
},

express-typescript-react: 404 (not found) frontend bundle file

I am making a full stack application, with Express(written in Typescript) and React. I am using webpack to bundle both backend and frontend.
I have two separate configs for webpack. One for frontend and the other one for backend.
Frontend config (webpack-fe.config.js)
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpack = require('clean-webpack-plugin');
const FRONTENDSRC = path.resolve(__dirname, 'frontend/src');
module.exports = {
target: 'web',
// #babel/polyfill is needed to use modern js functionalities in old browsers.
entry: ['#babel/polyfill', path.resolve(FRONTENDSRC, 'index.js')],
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle-fe.js'
},
module: {
rules: [
{
test: /\.jsx$|.js$/,
use: {
loader: 'babel-loader',
options: {
// To process async functions.
plugins: ['#babel/plugin-transform-async-to-generator']
}
},
exclude: /(node_modules|bower_components)/
},
{
test: /\.scss$|.sass/,
loaders: ['style-loader', 'css-loader', 'sass-loader']
}
]
},
resolve: {
modules: ['node_modules', FRONTENDSRC],
extensions: ['.js', '.jsx', '.ts', '.tsx', '.css', '.scss']
},
plugins: [
new HtmlWebpackPlugin({
template: path.resolve(FRONTENDSRC, 'index.html')
}),
new CleanWebpack(['./dist/bundle-be.js', './dist/index.html'])
],
watch: true,
mode: 'development',
devServer: {
contentBase: path.resolve(__dirname, 'dist'),
compress: true,
port: 9000
}
};
Backend config (webpack-be.config.js)
const path = require('path');
const CleanWebpack = require('clean-webpack-plugin');
const nodeExternals = require('webpack-node-externals');
const projectDir = 'string value used to define path';
module.exports = {
context: projectDir,
target: 'node',
// #babel/polyfill is needed to use modern js functionalities in old browsers.
entry: [
'#babel/polyfill',
path.join(projectDir, 'backend', 'src', 'index.ts')
],
output: {
path: path.join(projectDir, 'dist'),
filename: 'bundle-be.js',
publicPath: path.join(projectDir, 'dist')
},
module: {
rules: [
{
test: /\.js$/,
use: {
loader: 'babel-loader',
options: {
// To process async functions.
plugins: ['#babel/plugin-transform-async-to-generator']
}
},
exclude: /(node_modules|bower_components)/
},
{
test: /.ts$/,
loaders: ['ts-loader'],
exclude: /(node_modules|bower_components)/
}
]
},
resolve: {
modules: ['node_modules', path.join(projectDir, 'backend', 'src')],
extensions: ['.js', 'web.js', 'webpack.js', '.ts', '.tsx']
},
plugins: [new CleanWebpack([path.join(projectDir, 'dist', 'bundle-be.js')])],
watch: true,
externals: [nodeExternals()],
mode: 'development',
devtool: 'inline-source-map'
};
webpack.config.js
const feConfig = require('./webpack-fe.config');
const beConfig = require('./webpack-be.config');
module.exports = [feConfig, beConfig];
Here is the code for Server Initialization (index.ts)
import http from 'http';
import debug from 'debug';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import App from './server';
const config = require('../../webpack-be.config.js');
const compiler = webpack(config);
debug('ts-express:server');
class InitServer {
private port: number | boolean | string;
private server: any;
constructor() {
this.port = this.normalizePort(process.env.port || 7000);
App.set('port', this.port);
App.use(
webpackDevMiddleware(compiler, {
publicPath: config.output.publicPath
})
);
this.server = http.createServer(App);
this.server.listen(this.port);
this.server.on('error', this.onError);
this.server.on('listening', this.onListening);
}
private normalizePort = (val: number | string): number | string | boolean => {
let port: number = typeof val === 'string' ? parseInt(val, 10) : val;
if (isNaN(port)) return val;
else if (port >= 0) return port;
else return false;
};
private onError = (error: NodeJS.ErrnoException): void => {
if (error.syscall !== 'listen') throw error;
let bind =
typeof this.port === 'string' ? 'Pipe ' + this.port : 'Port ' + this.port;
switch (error.code) {
case 'EACCES':
console.error(`${bind} requires elevated privileges`);
process.exit(1);
break;
case 'EADDRINUSE':
console.error(`${bind} is already in use`);
process.exit(1);
break;
default:
throw error;
}
};
private onListening = (): void => {
console.log(`listening on ${this.port}`);
let addr = this.server.address();
let bind = typeof addr === 'string' ? `pipe ${addr}` : `port ${addr.port}`;
debug(`Listening on ${bind}`);
};
}
new InitServer();
Here is the server config file(server.ts)
import express from 'express';
import bodyParser from 'body-parser';
import path from 'path';
import { projectDir } from './shared/constants';
class App {
public express: express.Application;
constructor() {
this.express = express();
this.middleware();
this.routes();
}
private middleware(): void {
this.express.use(function(req, res, next) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Headers', '*');
next();
});
this.express.use(bodyParser.json());
this.express.use(bodyParser.urlencoded({ extended: false }));
}
private routes(): void {
this.express.get('/', function(req, res) {
res.sendFile(path.join(projectDir, 'dist', 'index.html'));
});
}
}
export default new App().express;
I use the following commands in the npm scripts:
"bundle": "webpack",
"serve": "node dist/bundle-be.js"
When I start the server, it serves my index.html file from the dist folder, but it gives me a 404 error for bundle-fe.js. I have checked that bundle-fe.js is generated in the dist folder. So why does it give me a 404 for bundle-fe.js ?
Thanks in advance!
Found it, I had to change the config file that I was using in index.ts file.
const config = require('../../webpack-fe.config.js'); // instead of webpack-be.config.js
Lol ^^ !!

Resources