How to use webpack to create a front end and a admin? - node.js

I am actually new on node.js. I am trying to create an app with admin and frontend using webpack and express. I have created an example app but now the problem is how I can create the app with the admin. Below I have shared my webpack config file
var webpack = require('webpack');
var path = require('path');
module.exports = {
entry: {
frontend: './src/index',
backend: './admin/index'
},
module: {
loaders: [
{
test: /\.js?$/, loader: 'babel', exclude: /node_modules/
},
{
test: /\.css$/,
loaders: [
'style?sourceMap',
'css?modules&importLoaders=1&localIdentName=[path]___[name]__[local]___[hash:base64:5]'
]
}
]
},
resolve: {
extensions: ['', '.js']
},
output: {
path: path.join(__dirname, '/public'),
publicPath: '/',
filename: 'bundle.js'
},
devServer: {
contentBase: './public',
hot: true
},
plugins: [
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
]
};
Webpack production configuration file
var config = require('./webpack.config.js');
var webpack = require('webpack');
config.plugins.push(
new webpack.DefinePlugin({
"process.env": {
"NODE_ENV": JSON.stringify("production")
}
})
);
config.plugins.push(
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
})
);
Is there any easy solution or what I can do now?

Related

webpack-hot-middleware only updates Css/Sass Once

I have a problem with webpack-hot-middleware and I'm not sure what I'm doing wrong.
In summary: Everytime I run the command node./ dev webpack runs and start to monitoring changes. This part is working great.
When I change my src / assets / js / index.js file, it refreshes the page after aply the changes. But with my src / assets / styles / index.scss file, it is only if that change is the first change I made after webpack start monitoring.
If I run node./ dev and change theindex.scss, the browser refresh after the changes are made in the output. On the second time, the browser does not refresh. Same happens if I change my index.js and tries to changeindex.scss.
In my Chrome console tab, it shows the following messages (when the page does not upload):
[HMR] bundle rebuilding client.js:242
[HMR] bundle rebuilt in 2407ms process-update.js:39
[HMR] Checking for updates on the server... process-update.js:110
[HMR] Nothing hot updated. process-update.js:119
[HMR] App is up to date.
Here is a Sample of my working code:
dev.js
const webpack = require('webpack');
const webpackMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');
const express = require('express');
const app = express();
const config = require('./webpack.dev.conf');
const DEFAULT_PORT = 3000;
const options = {
publicPath: config.output.publicPath
};
config.entry.main.push('webpack-hot-middleware/client?reload=true');
const compiler = webpack(config);
console.log('Starting the dev web server...');
app.use(webpackMiddleware(compiler, options));
app.use(webpackHotMiddleware(compiler));
app.listen(DEFAULT_PORT, (err) => {
if (err) {
console.log(err);
}
console.log('WebpackHotMiddleware is listening at http://localhost:3000/...');
});
webpack.dev.conf.js
const path = require('path');
const webpack = require('webpack');
const merge = require('webpack-merge');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const base = require('./webpack.base.conf');
const appHtmlTitle = 'Hello World';
process.env.NODE_ENV = 'development';
const dirSrc = path.join(__dirname, 'src');
process.noDeprecation = true;
module.exports = {
mode: 'development',
devtool: 'source-map',
output: {
path: path.join(__dirname, 'dev'),
publicPath: '/',
filename: 'assets/js/[name].js?[hash]'
},
optimization: {
splitChunks: {
chunks: 'all' // include all types of chunks
},
},
entry: {
main: [
path.join(dirSrc, 'assets', 'js', 'index'),
path.join(dirSrc, 'assets', 'styles', 'index.scss')
]
},
module: {
rules: [{
test: /\.html$/,
loader: 'html-loader',
options: { minimize: true }
},
{
enforce: 'pre',
test: /\.js$/,
exclude: [/node_modules/],
loader: 'eslint-loader'
},
{
test: /\.js?$/,
exclude: [/node_modules/],
loader: 'babel-loader'
},
// CSS / SASS
{
test: /\.(s)?css/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: { publicPath: '/' }
},
{ loader: 'css-loader' },
{ loader: 'sass-loader' }
]
},
// IMAGES
{
test: /\.(jpe?g|png|gif)$/i,
use: [
{
loader: 'file-loader',
options: {
publicPath: '/',
name: 'assets/images/[name].[ext]'
}
}
]
},
// FONTS
{
test: /\.(woff(2)?|ttf|eot|svg)(\?v=\d+\.\d+\.\d+)?$/,
loader: 'file-loader',
options: {
publicPath: '/',
name: 'assets/fonts/[name].[ext]'
}
}]
},
plugins: [
new CleanWebpackPlugin(['dev'], { verbose: false }),
new webpack.HotModuleReplacementPlugin(),
new webpack.NoEmitOnErrorsPlugin(),
new HtmlWebpackPlugin({
filename: path.join(__dirname, 'dev', 'index.html'),
template: 'src/index.ejs',
title: appHtmlTitle,
minify: {
removeComments: true,
collapseWhitespace: true,
removeAttributeQuotes: true
}
}),
new MiniCssExtractPlugin({
publicPath: '/',
filename: 'assets/css/[name].css?[hash]'
}),
new webpack.DefinePlugin({
PRODUCTION: JSON.stringify(false)
})
]
};

Cannot find module "fs" - at webpackMissingModule

My server starts and runs correctly, but when I hit the URL in the browser it gives an error "cannot find module 'fs'".
I tried to setting:
target: 'node', but it starts another error
node: { fs: 'empty' }, but then it gives an error "cannot find exports"
"use strict";
const webpack = require('webpack');
const argv = require('minimist')(process.argv.slice(2));
const DEBUG = !argv.release;
const path = require('path');
var plugins = [
new webpack.optimize.CommonsChunkPlugin({
names: ['common', 'vendors'],
filename: '[name].js',
minChunks: Infinity
}),
new webpack.optimize.OccurenceOrderPlugin(),
new webpack.DefinePlugin({
'process.env.NODE_ENV': DEBUG ? '"development"' : '"production"',
"process.argv.verbose": !!DEBUG
}),
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
jquery: "jquery"
})
].concat(DEBUG ? [] : [
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin({
minimize: true,
compress: {
warnings: true
}
}),
new webpack.optimize.AggressiveMergingPlugin()
]);
module.exports = {
entry: {
app: path.join(__dirname, '..', 'app', 'app.js'),
vendors: [
'react',
'react-dom',
'react-bootstrap',
'react-router',
'alt',
'lodash',
'superagent',
'react-router-role-authorization',
'react-validation-decorator'
]
},
output: {
publicPath: '/js/',
path: './wwwroot/js/',
filename: '[name].js',
chunkFilename: "[id].[name].js"
},
context: path.join(__dirname, '..'),
plugins: plugins,
cache: DEBUG,
debug: DEBUG,
watch: DEBUG,
stats: {
colors: true
},
resolve: {
extensions: ['', '.webpack.js', '.web.js', '.js', '.jsx', '.json']
},
module: {
loaders: [
{
test: /\.js$/,
exclude: /node_modules/,
loaders: ['babel-loader']
},
{
test: /\.(less|css)$/,
loaders: ["style", "css", "less"]
},
{
test: /\.(png|jpg|jpeg|gif|svg|woff|woff2)$/,
loader: 'url-loader?limit=10000'
},
{
test: /\.(eot|ttf|wav|mp3|mp4)$/,
loader: 'file-loader'
},
{
test: /\.json$/,
loader: 'json-loader'
}
]
},
node: {
net: 'mock',
dns: 'mock'
}
};
It should not give this error and work correctly.
I don't see any mention of the fs module in your posted webpack setup. So, my guess is that your output application (app.js?) is trying to require and use fs. Webpack is building a client-side, front-end application, one that will be loaded in the browser; fs is not available in the browser.
(Double-check and make sure you aren't trying to, for example, read and write files on the user's machine using fs inside your client-side application. That is not possible in a browser-based application. For an intro to the concept of web applications with a front end and back end, check out the article React App With Node Backend.)

Separate client and server in Webpack

Goal. Configuring app, which has: React, Webpack and MongoDB.
So, I've already setup Webpack for React and tried import Mongoose. The problem: React client-side and Mongoose - server-side, and because of that Webpack must have configurations for both. Using this answer: https://stackoverflow.com/a/37391247/7479176 I tried to configure Webpack. After that, I tried import Mongoose in my server.jsx file, but it didn't work.
Question. How to configure Webpack, so I can work with MongoDB?
Edited. I figured out how to rid of warnings (see Warnings):
output: {
filename: 'bundle.node.js',
libraryTarget: 'commonjs',
path: path.resolve(__dirname, 'dist')
},
externals: [
/^(?!\.|\/).+/i
],
But, when I added code into server.jsx (see server.jsx), it didn't log message in console.
Webpack configurations:
const path = require('path')
const webpack = require('webpack')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const CleanWebpackPlugin = require('clean-webpack-plugin')
module.exports = [
{
entry: {
index: './src/app/app.jsx'
},
devtool: 'inline-source-map',
devServer: {
port: 3000,
host: 'localhost',
historyApiFallback: true,
noInfo: false,
stats: 'minimal',
hot: true, // Tell the dev-server we're using HMR
contentBase: path.resolve(__dirname, './dist'),
publicPath: '/'
},
plugins: [
new webpack.NamedModulesPlugin(),
new webpack.HotModuleReplacementPlugin(), // Enable HMR
new CleanWebpackPlugin(['dist']),
new HtmlWebpackPlugin({
template: './src/index.html',
filename: 'index.html',
inject: 'body'
})
],
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader']
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
}
]
}
},
{
entry: {
index: './src/server/server.jsx'
},
target: 'node',
output: {
filename: 'bundle.node.js',
path: path.resolve(__dirname, 'dist')
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader']
}
]
}
}
]
server.jsx:
import mongoose from 'mongoose'
import '../config/database.js'
mongoose.Promise = global.Promise
mongoose.connect(config.database)
// check connection
mongoose.connection.once('open', () => console.log('Connected to MongoDB'))
// check for db errors
mongoose.connection.on('error', err => console.log(err))
Warnings:
WARNING in ./node_modules/mongoose/lib/drivers/index.js
10:13-49 Critical dependency: the request of a dependency is an expression
WARNING in ./node_modules/require_optional/index.js
82:18-42 Critical dependency: the request of a dependency is an expression
WARNING in ./node_modules/require_optional/index.js
90:20-44 Critical dependency: the request of a dependency is an expression
WARNING in ./node_modules/require_optional/index.js
97:35-67 Critical dependency: the request of a dependency is an expression
WARNING in ./node_modules/es6-promise/dist/es6-promise.js
Module not found: Error: Can't resolve 'vertx' in 'D:\Projects\JavaScriptProjects\pizzaday\node_modules\es6-promise\dist'
# ./node_modules/es6-promise/dist/es6-promise.js 131:20-30
# ./node_modules/mongodb/lib/mongo_client.js
# ./node_modules/mongodb/index.js
# ./node_modules/mongoose/lib/index.js
# ./node_modules/mongoose/index.js
# ./src/server/server.jsx
Solution. I used webpack-dev-middleware and webpack-hot-middleware with basic Express server. I tried launch MongoDB with React on webpack-dev-server and thats was main problem.
I made new server.js within separate folder following advice from Neil Lunn and setup basic Express server with middleware and split Webpack config into 3 separate files common, dev and prod.
This fragment of code in server.js helped me to run server and client together with Webpack which bonded everything together:
app.use(webpackDevMiddleware(compiler, {
publicPath: config.output.publicPath
}))
app.use(webpackHotMiddleware(compiler))
New Webpack config (webpack.common.js):
const webpack = require('webpack')
const path = require('path')
const CleanWebpackPlugin = require('clean-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
entry: {
app: [
'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=2000&reload=true',
'./src/index.jsx'
]
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new CleanWebpackPlugin(['dist']),
new HtmlWebpackPlugin({
template: './index.html',
filename: 'index.html',
inject: 'body'
})
],
output: {
filename: '[name].bundle.js',
path: path.resolve(__dirname, 'dist'),
publicPath: '/'
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /node_modules/,
use: ['babel-loader']
},
{
test: /\.css$/,
use: ['style-loader', 'css-loader']
}
]
}
}

How do i include my static assets in webpack and use them in angular2 app?

I have separate files for production and development environments of my app, my dev environment works fine, I am not getting how to i use my static assets in the webpack and use them in the app, they being directly accessed in my html and css files as shown below
authentication.component.html
<img src="/assets/images/myimage.png" />
authentication.component.css
#font-face {
font-family: "untitled-font-5";
src:url("/assets/fonts/untitled-font-5.eot");
src:url("/assets/fonts/untitled-font-5.eot?#iefix") format("embedded-opentype"),
url("/assets/fonts/untitled-font-5.woff") format("woff"),
url("/assets/fonts/untitled-font-5.ttf") format("truetype"),
url("/assets/fonts/untitled-font-5.svg#untitled-font-5") format("svg");
font-weight: normal;
font-style: normal;
}
This is my project's directory structure
and my webpack config files
common
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var helpers = require('./helpers');
module.exports = {
entry: {
'vendor': './src/vendor.ts',
'app': './src/app/main.ts'
},
resolve: {
extensions: ['', '.ts', '.js']
},
module: {
loaders: [
{
test: /\.ts$/,
loaders: ['awesome-typescript-loader', 'angular2-template-loader']
},
{
test: /\.html$/,
loader: 'html'
},
{
test: /\.(png|jpe?g|gif|svg|woff|woff2|ttf|eot|ico)$/,
loader: 'file?name=assets/[name].[hash].[ext]'
},
{
test: /\.css$/,
exclude: helpers.root('src', 'app'),
loader: ExtractTextPlugin.extract('style', 'css?sourceMap')
},
{
test: /\.css$/,
include: helpers.root('src', 'app'),
loader: 'raw'
}
]
},
plugins: [
new webpack.optimize.CommonsChunkPlugin({
name: ['app', 'vendor']
}),
new HtmlWebpackPlugin({
template: 'src/index.html'
}),
new webpack.ProvidePlugin({
jQuery: 'jquery',
$: 'jquery',
jquery: 'jquery',
"window.jQuery": "jquery"
})
]
};
dev
var webpackMerge = require('webpack-merge');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var commonConfig = require('./webpack.common.js');
var helpers = require('./helpers');
module.exports = webpackMerge(commonConfig, {
devtool: 'cheap-module-eval-source-map',
output: {
path: helpers.root('dist'),
publicPath: 'http://localhost:3000/',
filename: '[name].js',
chunkFilename: '[id].chunk.js'
},
plugins: [
new ExtractTextPlugin('[name].css')
],
devServer: {
historyApiFallback: true,
stats: 'minimal'
}
});
prod
var webpack = require('webpack');
var webpackMerge = require('webpack-merge');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var commonConfig = require('./webpack.common.js');
var helpers = require('./helpers');
const ENV = process.env.NODE_ENV = process.env.ENV = 'production';
module.exports = webpackMerge(commonConfig, {
devtool: 'source-map',
output: {
path: helpers.root('dist'),
publicPath: '/',
filename: '[name].[hash].js',
chunkFilename: '[id].[hash].chunk.js'
},
htmlLoader: {
minimize: false // workaround for ng2
},
plugins: [
new webpack.NoErrorsPlugin(),
new webpack.optimize.DedupePlugin(),
new webpack.optimize.UglifyJsPlugin({ // https://github.com/angular/angular/issues/10618
mangle: {
keep_fnames: true
}
}),
new ExtractTextPlugin('[name].[hash].css'),
new webpack.DefinePlugin({
'process.env': {
'ENV': JSON.stringify(ENV)
}
})
]
});

Webpack-dev-server showing directory list instead of the app page

I am building a progressive web app using react and i am using a webpack dev server.
My Web app config :
var webpack = require('webpack');
var path = require('path');
module.exports = {
entry: [
'webpack-dev-server/client?http://127.0.0.1:8080',
'webpack/hot/only-dev-server',
'./src/index.jsx'
],
output: {
path: path.join(__dirname,'public'),
filename: 'bundle.js',
publicPath: 'http://localhost:8080'
},
devServer: {
contentBase: "./public",
hot: true
},
resolve: {
modulesDirectories: ['node_modules','src'],
extensions: ['','.js']
},
module: {
loaders: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
loaders: ['react-hot','babel?presets[]=react,presets[]=react,presets[]=es2015']
}
]
},
plugins:[
new webpack.HotModuleReplacementPlugin(),
new webpack.NoErrorsPlugin()
]
};
This is my directory structure :
Please help me with this as i am not able to see my index.html.
Is there something wrong with my config file
Your index.html is in the folder "src"
so your webpack.config.js should like this:
devServer: {
contentBase: "./src",
hot: true
},

Resources