Deploying React App with webpack and Express.js - javascript

I'm developping an application using React, and webpack as the module bundler for the client part. For the server, I'm using Express.js.
For the client, I'm using webpack.config.dev.js for the configuration, and I use npm start to start a web server at localhost:3000.
For the server, I have the app.js file, and I use node bin/www to start the express server, but I have to give a different port to start the server, in this case, localhost:3100.
I have only a package.json for both, client, and server.
Is there a way to deploy both client and server in the same domain? If so, how can I do it? I would like from my client code to reference the endpoint as: /data/users, instead of doing localhost:3100/data/users.
See webpack config, express config, and package.json below (in case it helps):
webpack.config.dev.js:
import webpack from 'webpack';
import HtmlWebpackPlugin from 'html-webpack-plugin';
import autoprefixer from 'autoprefixer';
let node_dir = __dirname + '/node_modules';
let app_dir = __dirname + '/app';
export default {
resolve: {
extensions: ['', '.js', '.jsx'],
alias: {
'jquery': node_dir + '/jquery/dist/jquery.js',
'jquery-validation': node_dir + '/jquery-validation/dist/jquery.validate.js',
'jquery-placeholder': node_dir + '/jquery-placeholder/jquery.placeholder.js',
'jquery-oauth': node_dir + '/jquery-oauth/dist/jquery.oauth.js',
'bootstrap': node_dir + '/bootstrap/dist/js/bootstrap.min.js',
'owlcarousel':node_dir+'/owlcarousel/owl-carousel/owl.carousel.min.js',
'modernizr':node_dir + '/npm-modernizr/modernizr.js',
'jquery-shuffle':node_dir + '/shufflejs/dist/shuffle.js' ,
'jquery-stellar':node_dir + '/jquery.stellar/jquery.stellar.js',
'jquery-touchswipe':node_dir + '/jquery-touchswipe/jquery.touchSwipe.min.js'
},
modulesDirectories: ['js', 'node_modules']
},
debug: true,
devtool: 'cheap-module-eval-source-map', // more info:https://webpack.github.io/docs/build-performance.html#sourcemaps and https://webpack.github.io/docs/configuration.html#devtool
noInfo: true, // set to false to see a list of every file being bundled.
context: app_dir + "/app",
entry: {
// must be first entry to properly set public path
app: [app_dir+'/webpack-public-path',
'webpack-hot-middleware/client?reload=true',
app_dir+'/index']
},
target: 'web', // necessary per https://webpack.github.io/docs/testing.html#compile-and-test
output: {
// path: `${__dirname}/src`, // Note: Physical files are only output by the production build task `npm run build`.
path: `${__dirname}/app`,
publicPath: '/',
filename: 'bundle.js'
},
plugins: [
new webpack.ResolverPlugin(
new webpack.ResolverPlugin.DirectoryDescriptionFilePlugin("package.json", ["main"])
),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify('development'), // Tells React to build in either dev or prod modes. https://facebook.github.io/react/downloads.html (See bottom)
__DEV__: true
}),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
new HtmlWebpackPlugin({ // Create HTML file that includes references to bundled CSS and JS.
//template: 'src/index.ejs',
template: app_dir+'/index.html',
minify: {
removeComments: true,
collapseWhitespace: true
},
inject: true
}),
new webpack.ProvidePlugin({
$: "jquery",
jquery: "jquery",
"windows.jQuery": "jquery",
jQuery:"jquery",
}),
new webpack.optimize.CommonsChunkPlugin('vendors', 'vendors.js', Infinity)
],
module: {
loaders: [
{test: /\.jsx?$/, exclude: /node_modules/, loaders: ['babel']},
{test: /\.eot(\?v=\d+.\d+.\d+)?$/, loader: 'file'},
{test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/, loader: "url?limit=10000&mimetype=application/font-woff"},
{test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=application/octet-stream'},
{test: /\.svg(\?v=\d+\.\d+\.\d+)?$/, loader: 'url?limit=10000&mimetype=image/svg+xml'},
{test: /\.(jpe?g|png|gif)$/i, loader: 'file?name=[name].[ext]'},
{test: /\.ico$/, loader: 'file?name=[name].[ext]'},
{test: /(\.css|\.scss)$/, loaders: ['style', 'css?sourceMap', 'postcss', 'sass?sourceMap']},
]
},
postcss: ()=> [autoprefixer]
};
app.js for the server side:
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var routes = require('./routes/index');
var users = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', routes);
app.use('/users', users);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});
// error handlers
// development error handler
// will print stacktrace
if (app.get('env') === 'development') {
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: err
});
});
}
// production error handler
// no stacktraces leaked to user
app.use(function(err, req, res, next) {
res.status(err.status || 500);
res.render('error', {
message: err.message,
error: {}
});
});
module.exports = app;
And package.json:
{
"name": "dario-webapplication",
"version": "1.0.0",
"description": "Webapplication for Dario project",
"engines": {
"npm": ">=3"
},
"scripts": {
"server": "nodemon ./server/bin/www",
"preinstall": "node tools/nodeVersionCheck.js",
"setup": "node tools/setup/setupMessage.js && npm install && node tools/setup/setup.js",
"remove-demo": "babel-node tools/removeDemo.js",
"start-message": "babel-node tools/startMessage.js",
"prestart": "npm-run-all --parallel start-message remove-dist",
"start": "npm-run-all --parallel open:app lint:watch server",
"open:app": "babel-node tools/srcServer.js",
"open:dist": "babel-node tools/distServer.js",
"lint": "esw webpack.config.* app tools --color",
"lint:watch": "npm run lint -- --watch",
"clean-dist": "npm run remove-dist && mkdir dist",
"remove-dist": "rimraf ./dist",
"prebuild": "npm run clean-dist && npm run lint && npm run test",
"build": "babel-node tools/build.js && npm run open:dist",
"test": "mocha tools/testSetup.js \"app/**/*.spec.js\" --reporter progress",
"test:cover": "babel-node node_modules/isparta/bin/isparta cover --root app --report html node_modules/mocha/bin/_mocha -- --require ./tools/testSetup.js \"app/**/*.spec.js\" --reporter progress",
"test:cover:travis": "babel-node node_modules/isparta/bin/isparta cover --root app --report lcovonly _mocha -- --require ./tools/testSetup.js \"app/**/*.spec.js\" && cat ./coverage/lcov.info | node_modules/coveralls/bin/coveralls.js",
"test:watch": "npm run test -- --watch",
"open:cover": "npm run test:cover && open coverage/index.html"
},
"author": "Francisco Jose Parra Gonzalez",
"license": "MIT",
"dependencies": {
"bootstrap": "3.3.7",
"imports-loader": "0.6.5",
"jquery": "^1.11.1",
"jquery-oauth": "2.1.3",
"jquery-placeholder": "2.3.1",
"jquery-touchswipe": "1.6.15",
"jquery-ui": "^1.10.4",
"jquery-validation": "1.15.1",
"jquery.easing": "^1.3.2",
"jquery.stellar": "0.6.2",
"lightgallery": "1.2.21",
"npm-modernizr": "2.8.3",
"object-assign": "4.1.0",
"owlcarousel": "1.3.3",
"react": "15.3.0",
"react-bootstrap": "0.30.3",
"react-dom": "15.3.0",
"react-redux": "4.4.5",
"react-router": "2.6.1",
"react-router-redux": "4.0.5",
"redux": "3.5.2",
"redux-thunk": "2.1.0",
"shufflejs": "4.0.1",
"throttle-debounce": "1.0.1",
"body-parser": "~1.15.1",
"cookie-parser": "~1.4.3",
"debug": "~2.2.0",
"express": "~4.13.4",
"express-validator": "^2.20.8",
"jade": "~1.11.0",
"morgan": "~1.7.0",
"serve-favicon": "~2.3.0"
},
"devDependencies": {
"autoprefixer": "6.4.0",
"babel-cli": "6.11.4",
"babel-core": "6.11.4",
"babel-loader": "6.2.4",
"babel-plugin-react-display-name": "2.0.0",
"babel-plugin-transform-react-remove-prop-types": "0.2.9",
"babel-preset-es2015": "6.9.0",
"babel-preset-react": "6.11.1",
"babel-preset-react-hmre": "1.1.1",
"babel-preset-stage-1": "6.5.0",
"babel-register": "6.11.6",
"browser-sync": "2.14.0",
"chai": "3.5.0",
"chalk": "1.1.3",
"connect-history-api-fallback": "1.2.0",
"coveralls": "2.11.12",
"cross-env": "2.0.0",
"css-loader": "0.23.1",
"enzyme": "2.4.1",
"eslint": "3.2.2",
"eslint-plugin-import": "1.12.0",
"eslint-plugin-jsx-a11y": "2.0.1",
"eslint-plugin-react": "6.0.0",
"eslint-watch": "2.1.14",
"extract-text-webpack-plugin": "1.0.1",
"file-loader": "0.9.0",
"html-webpack-plugin": "2.22.0",
"isparta": "4.0.0",
"mocha": "3.0.1",
"mockdate": "1.0.4",
"node-sass": "3.8.0",
"npm-run-all": "2.3.0",
"open": "0.0.5",
"postcss-loader": "0.9.1",
"prompt": "1.0.0",
"react-addons-test-utils": "15.3.0",
"redux-immutable-state-invariant": "1.2.3",
"replace": "0.3.0",
"rimraf": "2.5.4",
"sass-loader": "4.0.0",
"sinon": "1.17.5",
"sinon-chai": "2.8.0",
"style-loader": "0.13.1",
"url-loader": "0.5.7",
"webpack": "1.13.1",
"webpack-dev-middleware": "1.6.1",
"webpack-hot-middleware": "2.12.2",
"webpack-md5-hash": "0.0.5"
},
"keywords": [],
"repository": {
"type": "git",
"url": ""
}
}

Maybe these boilerplate can help you.
And here in line 37 is what you looking for.
What initially gets run is bin/server.js, which does little more than enable ES6 and ES7 awesomeness in the server-side node code. It then initiates server.js. In server.js we proxy any requests to /api/* to the API server, running at localhost:3030. All the data fetching calls from the client go to /api/*. Aside from serving the favicon and static content from /static, the only thing server.js does is initiate delegate rendering to react-router. At the bottom of server.js, we listen to port 3000 and initiate the API server.

Related

How do you upgrade webpack-dev-server from v3 to v4?

I have been struggling with an issue with hot reloading where making edits in certain files would reload the app without those changes.
My initial solution was to update webpack and related modules. The first module I updated was webpack-dev-server. I went from v3 to v4 which immediately broke the app. All images and json files were getting 404'd when running the dev server.
Here is the original package.json:
{
...
"scripts": {
"dev": "set NODE_ENV=development && webpack serve --config config/webpack.dev.js --open",
"build": "set NODE_ENV=production && webpack --config config/webpack.prod.js",
"beatmarkers": "babel-node fetchAndFormatData/fetchAndFormatBeatMarkers.js"
},
"devDependencies": {
"#babel/cli": "^7.14.3",
"#babel/core": "^7.14.3",
"#babel/node": "^7.14.2",
"#babel/preset-env": "^7.14.4",
"clean-webpack-plugin": "^4.0.0-alpha.0",
"css-loader": "^5.2.6",
"file-loader": "^6.2.0",
"html-webpack-plugin": "^5.3.1",
"lodash.clonedeep": "^4.5.0",
"node-fetch": "^2.6.1",
"node-sass": "^6.0.0",
"sass-loader": "^11.1.1",
"style-loader": "^2.0.0",
"webpack": "^5.38.1",
"webpack-cli": "^4.7.0",
"webpack-dev-server": "^3.11.2",
"webpack-merge": "^5.7.3"
},
"dependencies": {
"bezier-easing": "^2.1.0",
"howler": "^2.2.3",
"pixi.js": "^6.2.0"
}
}
Here are the original webpack config files:
const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: './src/app.js',
plugins: [
new HtmlWebpackPlugin({
template: path.resolve(__dirname, '../src/template.html')
})
],
module: {
rules: [
{
test: /\.(png|jpe?g|gif|svg|ico|pvr|mp3|fnt)$/,
type: 'asset/resource'
},
{
test: /\.scss$/,
use: ['style-loader', 'css-loader', 'sass-loader']
}
]
}
};
const { merge } = require('webpack-merge');
const common = require('./webpack.common');
module.exports = merge(common, {
mode: 'development',
devServer: {
historyApiFallback: true,
},
output: {
publicPath: '/'
},
devtool: "source-map"
});
This configuration produces a sources structure in chrome that looks like this:
localhost:8080
main.js
(index)
assets/images
animations
fonts
interface
When I updated webpack-dev-server to the latest version, 4.11.1, the assets/images folder no longer exists. I haven't be able to figure out how to get it back. Any help would be deeply appreciated.

Build error when compiling Next.js app using next-pwa

I have been trying to run a local Next.js (v 12.2.2) project but for some reason, the dev script is not working as it should.
All the dependencies have been installed but still, I can't narrow down the reason why the script doesn't work.
The terminal looks like this after running the script
error - Please check your GenerateSW plugin configuration:
[WebpackGenerateSW] 'reactStrictMode' property is not expected to be
here. Did you mean property 'exclude'?
Here's the next.config.js file
const withPWA = require("next-pwa");
module.exports = withPWA({
reactStrictMode: true,
webpack5: true,
webpack: (config) => {
config.resolve.fallback = { fs: false };
return config;
},
pwa: {
dest: "public",
register: true,
disable: process.env.NODE_ENV === "development",
},
images: {
domains: ["pbs.twimg.com", "img.icons8.com", "gateway.moralisipfs.com", "ipfs.moralis.io", "lh3.googleusercontent.com", "www.artnews.com"],
},
// for running with docker
output: "standalone",
});
Here's the package.json file
{
"name": "musixverse-client",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint",
"postbuild": "next-sitemap"
},
"dependencies": {
"#headlessui/react": "^1.6.6",
"#heroicons/react": "^1.0.5",
"#walletconnect/web3-provider": "^1.7.8",
"#web3auth/web3auth": "^1.1.1",
"axios": "^0.26.1",
"country-state-city": "^3.0.1",
"magic-sdk": "^8.0.1",
"moralis": "^1.10.0",
"next": "^12.2.2",
"next-pwa": "^5.4.4",
"next-sitemap": "^3.1.16",
"next-themes": "^0.0.15",
"persona": "^4.6.0",
"react": "^17.0.2",
"react-datepicker": "^4.8.0",
"react-dom": "17.0.2",
"react-image-crop": "^8.6.12",
"react-moralis": "^1.4.0",
"react-select": "^5.4.0",
"styled-components": "^5.3.5",
"web3": "^1.7.4"
},
"devDependencies": {
"autoprefixer": "^10.4.7",
"eslint": "8.6.0",
"eslint-config-next": "12.0.7",
"postcss": "^8.4.14",
"tailwindcss": "^3.1.4"
}
}
node-version: 16.17.0,
npm-version: 8.19.0
Your usage of the next-pwa plugin is incorrect as of version 5.6.0. A breaking change was introduced that changed the plugin signature (see next-pwa/releases/tag/5.6.0).
Start from version 5.6.0. This plugin function signature has been
changed to follow the recommended pattern from next.js. Mainly
extracting pwa config from mixing into rest of the next.js config.
From version 5.6.0, according to the documentation, your config should look like the following.
// `next-pwa` config should be passed here
const withPWA = require("next-pwa")({
dest: "public",
register: true,
disable: process.env.NODE_ENV === "development",
});
// Use `withPWA` and pass general Next.js config
module.exports = withPWA({
reactStrictMode: true,
webpack5: true,
webpack: (config) => {
config.resolve.fallback = { fs: false };
return config;
},
images: {
domains: ["pbs.twimg.com", "img.icons8.com", "gateway.moralisipfs.com", "ipfs.moralis.io", "lh3.googleusercontent.com", "www.artnews.com"]
},
output: "standalone"
});

webpack failed to start react project

I am learning to use webpack to develop a react project, but I cannot start local services locally. It reports the following error.
ERROR in ./src/index.js 5:16
Module parse failed: Unexpected token (5:16)
You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
| import App from './App';
|
> ReactDOM.render(<App />, document.getElementById('root'));
|
I suspect this is a babel compilation problem, but I have configured babel-loader, but it does not work. I Googled this issue for a long time, but I still didn't find the problem. Can you help me? Thanks!
And this is my configuration files.
// webpack.common.js
const path = require('path');
const commonConfig = {
entry: [
'babel-polyfill',
'../src/index.js'
],
output: {
path: path.resolve(__dirname, 'dist'),
filename: 'bundle.js'
},
plugins: [
new HtmlWebpackPlugin({
template: path.resolve(__dirname, 'dist/index.html')
})
],
module: {
rules: [{
test: /\.(jsx?|tsx?)$/,
loader: 'babel-loader',
exclude: /node_modules/,
}]
}
};
module.exports = commonConfig;
// webpack.dev.js
const merge = require('webpack-merge');
const commonConfig = require('./webpack.common.js');
const path = require('path');
const devConfig = merge(commonConfig, {
mode: 'development',
devServer: {
contentBase: path.join(__dirname, 'dist'),
compress: true,
port: 3000
}
})
module.exports = devConfig;
// package.json
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "webpack-dev-server",
},
"devDependencies": {
"#babel/core": "^7.11.4",
"#babel/preset-env": "^7.11.0",
"#babel/preset-react": "^7.10.4",
"babel-core": "^6.26.3",
"babel-loader": "^8.1.0",
"babel-polyfill": "^6.26.0",
"babel-preset-env": "^1.7.0",
"babel-preset-es2015": "^6.24.1",
"babel-preset-react": "^6.24.1",
"html-webpack-plugin": "^4.3.0",
"webpack": "^4.44.1",
"webpack-cli": "^3.3.12",
"webpack-dev-server": "^3.11.0"
},
"dependencies": {
"react": "^16.13.1",
"react-dom": "^16.13.1"
// .babelrc
{
"presets": ["env", "react"]
}
I found out where the problem was. I didn’t specify the webpack.dev.js file for the npm run start command in the scripts of package.json, and it worked after making the following changes.
"scripts": {
"start": "webpack-dev-server --config webpack/webpack.dev.js",
},

Angular Fire with Universal SSR | Everything works, but the problem is while building my app [duplicate]

I'm dealing with this issue for almost two weeks now. I tried a lot of workarounds but none seems to be working. I've installed angular-fire and firebase to its latest version, tried ng add #angular/fire, configured custom webpack.config.ts, tried rolling back to every suggested previous version. None fixed this issue.
The Actual Error:
de-10#de10-LIFEBOOK-A555:~/Desktop$ node dist/server.js
internal/modules/cjs/loader.js:797
throw err;
^
Error: Cannot find module 'firebase/app'
Require stack:
- /home/de-10/Desktop/dist/server.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:794:15)
at Function.Module._load (internal/modules/cjs/loader.js:687:27)
at Module.require (internal/modules/cjs/loader.js:849:19)
at require (internal/modules/cjs/helpers.js:74:18)
at Object.<anonymous> (/home/de-10/Desktop/dist/server.js:125276:18)
at __webpack_require__ (/home/de-10/Desktop/dist/server.js:20:30)
at Module.<anonymous> (/home/de-10/Desktop/dist/server.js:125199:70)
at __webpack_require__ (/home/de-10/Desktop/dist/server.js:20:30)
at Module.<anonymous> (/home/de-10/Desktop/dist/server.js:124984:78)
at __webpack_require__ (/home/de-10/Desktop/dist/server.js:20:30) {
code: 'MODULE_NOT_FOUND',
requireStack: [ '/home/de-10/Desktop/dist/server.js' ]
}
And I can't let go of Firebase cause then I face:
ERROR in ../node_modules/#angular/fire/auth/auth.d.ts:4:28 - error TS2307: Cannot find module 'firebase/app'.
4 import { User, auth } from 'firebase/app';
~~~~~~~~~~~~~~
../node_modules/#angular/fire/firebase.app.module.d.ts:2:74 - error TS2307: Cannot find module 'firebase/app'.
2 import { auth, database, messaging, storage, firestore, functions } from 'firebase/app';
~~~~~~~~~~~~~~
../node_modules/#angular/fire/firestore/collection-group/collection-group.d.ts:2:27 - error TS2307: Cannot find module 'firebase/app'.
~~~~~~~~~~~~~
.
.
.
app/services/notification.service.ts:29:38 - error TS2339: Property 'id' does not exist on type 'QueryDocumentSnapshot<unknown>'.
29 id: snap.payload.doc.id,
~~
app/services/notification.service.ts:68:35 - error TS2339: Property 'type' does not exist on type 'DocumentChange<unknown>'.
68 return snap.payload.type
~~~~
.
.
.
package.json
{
"name": "universal-ssr",
"version": "0.0.0",
"license": "MIT",
"scripts": {
"ng": "ng",
"start": "npm run build:ssr",
"staging": "npm run build:ssr-staging && npm run serve:ssr",
"production": "npm run build:ssr && npm run serve:ssr",
"prod": "npm run build:ssr-production && npm run serve:ssr",
"build": "ng build --prod",
"test": "ng test",
"dev-start": "ng serve",
"ng serve": "ng serve --aot",
"lint": "ng lint",
"e2e": "ng e2e",
"build:ssr": "npm run build:client-and-server-bundles && npm run webpack:server",
"build:ssr-staging": "npm run build:client-and-server-bundles-staging && npm run webpack:server",
"build:ssr-production": "npm run build:client-and-server-bundles-production && npm run webpack:server",
"serve:ssr": "node dist/server.js",
"build:client-and-server-bundles": "ng build --prod --build-optimizer && ng run universal-ssr:server --bundleDependencies all",
"build:client-and-server-bundles-staging": "ng build --c=staging --build-optimizer=true --stats-json && ng run universal-ssr:server",
"build:client-and-server-bundles-production": "ng build --c=production --build-optimizer=true && ng run universal-ssr:server --bundleDependencies all",
"webpack:server": "webpack --config webpack.config.js --progress --colors",
"webpack:analyzer": "webpack-bundle-analyzer dist/browser/stats.json",
"compodoc": "npx compodoc -p src/tsconfig.app.json -o"
},
"private": true,
"dependencies": {
"#angular/animations": "^8.2.14",
"#angular/cdk": "^5.2.5",
"#angular/common": "^8.2.14",
"#angular/compiler": "^8.2.14",
"#angular/core": "^8.2.14",
"#angular/fire": "^5.4.2",
"#angular/forms": "^8.2.14",
"#angular/material": "^5.2.5",
"#angular/platform-browser": "^8.2.14",
"#angular/platform-browser-dynamic": "^8.2.14",
"#angular/platform-server": "^8.2.14",
"#angular/pwa": "^0.803.24",
"#angular/router": "^8.2.14",
"#angular/service-worker": "^8.2.14",
"#ng-bootstrap/ng-bootstrap": "^4.0.0",
"#nguniversal/express-engine": "^6.1.0",
"#nguniversal/module-map-ngfactory-loader": "^6.1.0",
"angular2-datetimepicker": "^1.1.1",
"bootstrap": "^4.4.1",
"city-timezones": "^1.2.0",
"core-js": "^2.6.11",
"cors": "^2.8.4",
"express": "^4.17.1",
"firebase": "^7.13.1",
"jquery": "^3.4.1",
"moment-timezone": "^0.5.27",
"ng-bootstrap": "^1.6.3",
"ng2-search-filter": "^0.5.1",
"ngx-clipboard": "12.2.1",
"ngx-google-places-autocomplete": "^2.0.4",
"ngx-pagination": "^3.3.1",
"ngx-spinner": "^2.0.0",
"ngx-toggle-switch": "^2.0.5",
"ngx-ui-switch": "^8.3.0",
"rxjs": "^6.5.4",
"rxjs-compat": "^6.0.0",
"save": "^2.4.0",
"ts-loader": "^4.0.0",
"tslib": "^1.10.0",
"uuid": "^3.4.0",
"zone.js": "~0.9.1"
},
"devDependencies": {
"#angular-devkit/build-angular": "~0.803.23",
"#angular/cli": "^8.3.23",
"#angular/compiler-cli": "^8.2.14",
"#angular/http": "^7.2.16",
"#angular/language-service": "^8.2.14",
"#types/jasmine": "2.8.3",
"#types/jasminewd2": "^2.0.8",
"#types/node": "^6.14.9",
"codelyzer": "^5.0.1",
"jasmine-core": "~2.8.0",
"jasmine-spec-reporter": "~4.2.1",
"karma": "^4.4.1",
"karma-chrome-launcher": "~2.2.0",
"karma-coverage-istanbul-reporter": "^2.1.1",
"karma-jasmine": "~1.1.0",
"karma-jasmine-html-reporter": "^0.2.2",
"protractor": "5.4.2",
"ts-node": "~4.1.0",
"tslint": "~5.9.1",
"typescript": "~3.5.3",
"webpack-cli": "^3.1.0"
}
}
webpack.config.js:
// Work around for https://github.com/angular/angular-cli/issues/7200
const path = require('path');
const webpack = require('webpack');
// change the regex to include the packages you want to exclude
const regex = /firebase\/(app|firestore)/;
module.exports = {
mode: 'production',
entry: {
// This is our Express server for Dynamic universal
server: './server.ts'
},
externals: {
'./dist/server/main': 'require("./server/main")'
},
target: 'node',
node: {
__dirname: false,
__filename: false,
},
resolve: { extensions: ['.ts', '.js'] },
target: 'node',
mode: 'none',
// this makes sure we include node_modules and other 3rd party libraries
externals: [/node_modules/, function (context, request, callback) {
// exclude firebase products from being bundled, so they will be loaded using require() at runtime.
if (regex.test(request)) {
return callback(null, 'commonjs ' + request);
}
callback();
}],
optimization: {
minimize: false
},
output: {
// Puts the output at the root of the dist folder
path: path.join(__dirname, 'dist'),
filename: '[name].js'
},
module: {
noParse: /polyfills-.*\.js/,
rules: [
{ test: /\.ts$/, loader: 'ts-loader' },
{
// Mark files inside `#angular/core` as using SystemJS style dynamic imports.
// Removing this will cause deprecation warnings to appear.
test: /(\\|\/)#angular(\\|\/)core(\\|\/).+\.js$/,
parser: { system: true },
},
]
},
plugins: [
new webpack.ContextReplacementPlugin(
// fixes WARNING Critical dependency: the request of a dependency is an expression
/(.+)?angular(\\|\/)core(.+)?/,
path.join(__dirname, 'src'), // location of your src
{} // a map of your routes
),
new webpack.ContextReplacementPlugin(
// fixes WARNING Critical dependency: the request of a dependency is an expression
/(.+)?express(\\|\/)(.+)?/,
path.join(__dirname, 'src'),
{}
)
]
};
server.ts:
import 'zone.js/dist/zone-node';
import * as express from 'express';
/* const express = require('express');
const join = require('path'); */
const compression = require('compression')
import { join } from 'path';
// Express server
const app = express();
// gzip
app.use(compression())
const PORT = process.env.PORT || 4000;
const DIST_FOLDER = join(__dirname, 'browser');/* 'dist/browser' */
// * NOTE :: leave this as require() since this file is built Dynamically from webpack
const { AppServerModuleNgFactory, LAZY_MODULE_MAP, ngExpressEngine, provideModuleMap } = require('./dist/server/main');
// Our Universal express-engine (found # https://github.com/angular/universal/tree/master/modules/express-engine)
app.engine('html', ngExpressEngine({
bootstrap: AppServerModuleNgFactory,
providers: [
provideModuleMap(LAZY_MODULE_MAP)
]
}));
app.set('view engine', 'html');
app.set('views', DIST_FOLDER);
// Serve static files from /browser
app.get('*.*', express.static(DIST_FOLDER, {
maxAge: '1y'
}));
// All regular routes use the Universal engine
app.get('*', (req, res) => {
res.render('index', { req });
});
// Start up the Node server
app.listen(PORT, () => {
console.log(`Node Express server listening on http://localhost:${PORT}`);
});
You're getting this error because you're excluding firebase dependencies with this =>
const regex = /firebase\/(app|firestore)/;
module.exports = {
// this makes sure we include node_modules and other 3rd party libraries
externals: [/node_modules/, function (context, request, callback) {
// exclude firebase products from being bundled, so they will be loaded using require() at runtime.
if (regex.test(request)) {
return callback(null, 'commonjs ' + request);
}
callback();
}],
};
Remove this
if (regex.test(request)) {
return callback(null, 'commonjs ' + request);
}
and your app will be fine.
One workaround is to install npm packages (firebase and #angular/fire) beside the dist folder and then run the deployment script.

How to build the static file for use in deployment

With my current configuration of node and webpack, I am able to run the dev-server and develop my application.
I am however unable to create the static bundle.js that i could use for a deployment on my website.
How can I configure my webpack.js files and package.json command to make it build the required bundle file ?
When I run npm build, nothing happens
When I run npm deploy, i get the following error message :
Usage: npm <command>
where <command> is one of:
access, add-user, adduser, apihelp, author, bin, bugs, c,
cache, completion, config, ddp, dedupe, deprecate, dist-tag,
dist-tags, docs, edit, explore, faq, find, find-dupes, get,
help, help-search, home, i, info, init, install, issues, la,
link, list, ll, ln, login, logout, ls, outdated, owner,
pack, ping, prefix, prune, publish, r, rb, rebuild, remove,
repo, restart, rm, root, run-script, s, se, search, set,
show, shrinkwrap, star, stars, start, stop, t, tag, team,
test, tst, un, uninstall, unlink, unpublish, unstar, up,
update, upgrade, v, verison, version, view, whoami
npm <cmd> -h quick help on <cmd>
npm -l display full usage info
npm faq commonly asked questions
npm help <term> search for help on <term>
npm help npm involved overview
Specify configs in the ini-formatted file:
C:\Users\Sébastien\.npmrc
or on the command line via: npm <command> --key value
Config info can be viewed via: npm help config
Following is my configuration :
package.json
{
"license": "UNLICENSED",
"private": true,
"version": "1.0.0",
"webPath": "web/",
"nodePath": "node_modules/",
"devDependencies": {
"autoprefixer": "^6.3.1",
"exports-loader": "^0.6.2",
"grunt": "^0.4.5",
"grunt-autoprefixer": "^3.0.3",
"grunt-contrib-concat": "^0.5.1",
"grunt-contrib-cssmin": "^0.14.0",
"grunt-contrib-less": "^1.1.0",
"grunt-contrib-uglify": "^0.11.0",
"grunt-contrib-watch": "^0.6.1",
"grunt-css-url-rewrite": "^0.3.5",
"grunt-cssjoin": "^0.3.0",
"grunt-postcss": "^0.7.1",
"imports-loader": "^0.6.5",
"matchdep": "^1.0.0",
"redux-devtools": "^3.0.2",
"redux-devtools-dock-monitor": "^1.0.1",
"redux-devtools-log-monitor": "^1.0.4",
"webpack-shell-plugin": "^0.4.2"
},
"repository": {
"type": "git",
"url": ""
},
"dependencies": {
"babel-core": "^6.4.0",
"babel-loader": "^6.2.1",
"babel-plugin-transform-runtime": "^6.4.3",
"babel-polyfill": "^6.3.14",
"babel-preset-es2015": "^6.3.13",
"babel-preset-react": "^6.3.13",
"babel-preset-stage-0": "^6.3.13",
"babel-runtime": "^6.3.19",
"grunt-postcss": "^0.7.1",
"history": "^1.17.0",
"i18next": "^2.5.1",
"isomorphic-fetch": "^2.2.1",
"lodash": "^4.11.1",
"radium": "^0.16.2",
"rc-switch": "^1.4.2",
"react": "^0.14.6",
"react-dom": "^0.14.6",
"react-hot-loader": "^1.3.0",
"react-redux": "^4.1.2",
"react-router": "^1.0.3",
"react-router-redux": "^3.0.0",
"redux": "^3.1.6",
"redux-thunk": "^2.1.0",
"selfupdate": "^1.1.0",
"webpack": "^1.12.11",
"webpack-dev-server": "^1.14.1",
"whatwg-fetch": "^0.11.0"
},
"scripts": {
"start": "node webpack.dev-server.js",
"build": "webpack",
"deploy": "NODE_ENV=production webpack -p --config webpack.production.config.js"
}
}
webpack.config.js
var path = require('path');
var webpack = require('webpack');
var node_modules_dir = path.join(__dirname, 'node_modules');
var devFlagPlugin = new webpack.DefinePlugin({
__DEV__: JSON.stringify(JSON.parse(process.env.DEBUG || 'false'))
});
console.log(__dirname);
var config = {
entry: [
'babel-polyfill',
'webpack-dev-server/client?http://127.0.0.1:3000',
'webpack/hot/only-dev-server',
'./app/Resources/react/app.js'
],
output: {
path: path.join(__dirname, 'web/js'),
filename: 'bundle.js',
publicPath: 'http://127.0.0.1:3000/static/'
},
debug: true,
devtool: 'eval',
plugins: [
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin(),
devFlagPlugin
],
module: {
loaders: [
{
loaders: ["react-hot","babel-loader?plugins=transform-runtime&presets[]=es2015&presets[]=stage-0&presets[]=react"],
test: /\.js$/,
include: path.join(__dirname, 'app/Resources/react')
}
]
}
};
module.exports = config;
/*
new webpack.ProvidePlugin({
'fetch': 'imports?this=>global!exports?global.fetch!whatwg-fetch'
})
*/
webpack.dev-server.js
var webpack = require('webpack');
var WebpackDevServer = require('webpack-dev-server');
var config = require('./webpack.config');
new WebpackDevServer(webpack(config), {
publicPath: config.output.publicPath,
hot: true,
historyApiFallback: true,
quiet: false,
noInfo: false,
contentBase: "./assets"
}).listen(3000, 'localhost', function (err, result) {
if (err) {
console.log(err);
}
console.log('Listening at localhost:3000');
});
webpack.production.config.js
var path = require('path');
var node_modules_dir = path.resolve(__dirname, 'node_modules');
var config = {
entry: [
'babel-polyfill',
'./app/Resources/react/app.js'
],
output: {
path: path.join(__dirname, 'web/js'),
filename: 'bundle.js'
},
module: {
loaders: [
{
loaders: ["babel-loader?plugins=transform-runtime&presets[]=es2015&presets[]=stage-0&presets[]=react"],
test: /\.js$/,
include: path.join(__dirname, 'src/react')
}
]
}
};
module.exports = config;
you missed run
npm run deploy
run is required for all scripts. To help with common tasks npm knows how to use several preconfigured scripts such as start and test which is why npm start is an equivalent of npm run start.

Categories