No autoreload page , webpack-dev-server - javascript

All work correctly , webpack-dev-server compiling after change in files, but browser folder no automatically reload
Packages installed:
"webpack": "^5.21.2",
"webpack-cli": "^4.5.0",
"webpack-dev-server": "^3.11.2"
Thanks
code in webpack.config.js
const path = require('path')
const {CleanWebpackPlugin} = require('clean-webpack-plugin')
const HTMLWebpackPlugin = require('html-webpack-plugin')
const CopyPlugin = require('copy-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const isProd = process.env.NODE_ENV === 'production'
const isDev = !isProd
console.log(isDev)
const filename = ext => isDev ? `bundle.${ext}` : `bundle.[hash].${ext}`
const jsLoaders = () => {
const loaders = [
{
loader: 'babel-loader',
options: {
presets: ['#babel/preset-env']
}
}
]
if (isDev) {
loaders.push('eslint-loader')
}
return loaders
}
module.exports = {
context: path.resolve(__dirname, 'src'),
mode: 'development',
entry: ['#babel/polyfill', './index.js'],
output: {
filename: filename('js'),
path: path.resolve(__dirname, 'dist')
},
resolve: {
extensions: ['.js'],
alias: {
'#': path.resolve(__dirname, 'src'),
'#core': path.resolve(__dirname, 'src/core')
}
},
devtool: isDev ? 'source-map' : false,
devServer: {
port: 3000,
hot: isDev,
},
***
}
}
NPM scripts to start(y use 'start' script)
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "cross-env NODE_ENV=development webpack serve --hot --inline --open",
"build": "cross-env NODE_ENV=production webpack --mode production"
},

Try upgrading to the beta webpack-dev-server (v4)

Related

What could I be missing in my webpack.config.js file to have "npm start" not work?

What could I be missing in my webpack.config.js file to have "npm start" work?
To provide some context, I am currently taking a tutorial herer: https://www.awwwards.com/academy/course/building-an-immersive-creative-website-from-scratch-without-frameworks) on which part of it is creating a boilerplate. At the moment, the tutorial has me setting up the package.json, webpack.config.js, and webpack.config.development.js. I am currently running into an issue where when I run "npm start", a message in my terminal pops up with
Configuration file found but no entry configured.
Any ideas? I will paste all the code for reference. Also, would it be recommended for now to skip over the Boilerplate introduction as it isn't needed? Hearing that might be a solid option as well.
Webpack.config.build.js
const path = require('path')
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
const { merge } = require('webpack-merge')
const config = require('./webpack.config')
module.exports = merge(config, {
mode: 'production',
output: {
path: path.join(__dirname, 'public')
},
plugins: [
new CleanWebpackPlugin()
]
})
Webpack.config.js
const path = require('path')
const webpack = require('webpack')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const MiniCssExtractPlugin = require('mini-css-extract-plugin')
const IS_DEVELOPMENT = process.env.NODE_ENV === 'dev'
const dirApp = path.join(__dirname, 'app')
const dirAssets = path.join(__dirname, 'assets')
const dirStyles = path.join(__dirname, 'styles')
Webpack.config.development.js
const { merge } = require('webpack-merge')
const path = require('path')
const config = require('./webpack.config')
module.exports = merge(config, {
mode: 'development',
devtool: 'inline-source-map',
devServer: {
writeToDisk: true
},
output: {
path: path.resolve(__dirname, 'public')
}
})
Package.json
{
"name": "floema",
"version": "1.0.0",
"scripts": {
"build": "webpack -p --progress --config webpack.config.build.js",
"development": "webpack serve --progress --config webpack.config.development.js",
"start": "npm run development"
},
"author": "Chris",
"devDependencies": {
"clean-webpack-plugin": "^4.0.0",
"copy-webpack-plugin": "^10.1.0",
"mini-css-extract-plugin": "^2.4.5",
"webpack": "^2.1.0-beta.22",
"webpack-cli": "^4.9.1",
"webpack-dev-server": "^4.6.0",
"webpack-merge": "^5.8.0"
}
}
you are not exporting anything from webpack.config.js. Besides, this file is not a valid config file..
You should be exporting a config object from webpack.config.js, like so
module.exports = {
entry: './src/index.js',
output: {
path: __dirname,
publicPath: '/',
filename: 'bundle.js'
},
...
}

Using webpack with express and ejs for frontend and/or server

I am struggling a bit to find a solution to using webpack on the both the frontend and the server part of a nodejs project.
I am building an express solution with different API endpoints and a frontend that uses EJS for templating that will use these endpoints for data handling.
Basically what I am trying to achieve is to using webpack to compile my SCSS and JS on the frontend and also a solution that will compile EJS and inject the CSS and JS bundles into the frontend.
My current server.js
const express = require('express')
const formidable = require('express-formidable');
const session = require('express-session')
const bodyparser = require('body-parser')
const app = express()
const path = require('path');
const auth = require('./app/middleware/authorization/auth')
const upload = require('./app/middleware/filehandling/upload')
app.set('port', process.env.PORT || 8080);
app.set('view engine', 'ejs')
app.set('views', path.join('views'));
app.use(session({
secret: hash.getRandomString(16),
resave: true,
saveUninitialized: true
}))
app.use(express.json())
app.use('/public', express.static(path.resolve(__dirname, 'public')));
app.use(formidable());
app.use(passport.initialize());
app.use(passport.session());
app.use(bodyparser.urlencoded({ extended: true }))
app.use(bodyparser.json())
//DIFFERENT ROUTES DOWN HERE
app.listen(3000, () => {
console.log('listening on port 3000')
})
My folder structure is
public
- upload/
src
- scss/
- index.js
views
- partials/
- index.ejs
- login.ejs
I have a current webpack.config.dev.js that I am using for static HTML/CSS/JS project that are building and compiling SCSS and JS into bundles.
const path = require('path');
const webpack = require('webpack');
const HTMLWebpackPlugin = require('html-webpack-plugin');
// const ExtractText = require('extract-text-webpack-plugin');
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const devMode = process.env.NODE_ENV !== 'production'
const dirNodeModules = 'node_modules';
const dirAPP = path.join(__dirname, 'src/app');
const dirAssets = path.join(__dirname, 'src/assets');
const packageJson = require('./package.json')
var config = {
entry: {
bundle: path.join(dirAPP, 'index')
},
resolve: {
modules: [
dirNodeModules,
dirAPP,
dirAssets
]
},
plugins: [
new webpack.DefinePlugin({
devMode: devMode
}),
new HTMLWebpackPlugin({
template: path.join('src', 'index.html'),
inject: true
}),
new MiniCssExtractPlugin({
filename: packageJson.name + '.[chunkhash].min.css'
})
],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: ['babel-loader', 'eslint-loader']
},
{
test: /\.(sa|sc|c)ss$/,
use: [
MiniCssExtractPlugin.loader,
'css-loader',
{
loader: 'postcss-loader',
options: {
ident: 'postcss',
sourceMap: true,
config: {
path: 'postcss.config.js'
}
},
loader: 'sass-loader',
options: {
sourceMap: true
}
}
]
},
{
test: /\.(eot|svg|ttf|woff|woff2)$/,
use: 'file?=name/fonts/[name].[ext]'
},
{
test: /\.(jpe?g|png|gif|svg)$/i,
use: [{
loader: 'file-loader',
options: {
name: '[name]-[hash:8].[ext]',
pluginPath: dirAssets + '/images/',
outputPath: dirAssets + '/images/'
}
}]
}]
}
}
module.exports = config;
And a webpack.config.build.js
const path = require('path');
const merge = require('webpack-merge');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const webpackConfig = require('./webpack.config');
const packageJson = require('./package.json');
module.exports = merge(webpackConfig, {
devtool: 'source-map',
output: {
path: path.join(__dirname, 'dist'),
filename: packageJson.name + '.[chunkhash].js'
},
plugins: [
new CleanWebpackPlugin(['dist'])
]
});
Which I call using
"dev": "cross-env NODE_ENV=dev webpack-dev-server --progress --mode development --config webpack.config.dev.js",
"build": "webpack -p --progress --mode production --config webpack.config.build.js"
I am a bit unsure how I can achieve this.

Vuejs: Cannot resolve module 'fs'

I installed resource-bundle package:
npm install resource-bundle
But for building:
npm run build
gets error:
'cannot resolve module 'fs' '. what should i do?
webpack.base.conf.js:
'use strict'
const path = require('path')
const utils = require('./utils')
const config = require('../config')
const vueLoaderConfig = require('./vue-loader.conf')
function resolve (dir) {
return path.join(__dirname, '..', dir)
}
module.exports = {
entry: {
app: './src/main.js'
},
output: {
path: config.build.assetsRoot,
filename: '[name].js',
publicPath: process.env.NODE_ENV === 'production'
? config.build.assetsPublicPath
: config.dev.assetsPublicPath
},
resolve: {
extensions: ['.js', '.vue', '.json'],
alias: {
'vue$': 'vue/dist/vue.esm.js',
'#': resolve('src')
}
},
module: {
...
}
}
node: {
fs: 'empty'
}
*added fs: 'empty' at the end.
Try to add the following to your Webpack config:
node: {
fs: "empty"
}

Webpack dev middleware for all routes

I configured webpack dev middleware, when I go to index page / all works fine, otherwise page Not Found, how to make work dev server for all paths ?
const Koa = require('koa');
const webpack = require('webpack');
const devMiddleware = require('koa-webpack-dev-middleware')
const path = require('path');
const fs = require('fs');
const PORT = 3000;
const app = new Koa();
const config = require('./webpack.config');
const compiler = webpack(config);
app.use(devMiddleware(compiler, {
publicPath: config.output.publicPath,
historyApiFallback: true,
stats: { colors: true },
}));
app.listen(PORT, function () {
console.log(`Dev Server port: "${3000}"`);
});
webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CleanWebpackPlugin = require('clean-webpack-plugin');
module.exports = {
entry: './src/index.js',
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist'),
publicPath: '/',
},
devtool: 'inline-source-map',
plugins: [
new CleanWebpackPlugin(['dist']),
new HtmlWebpackPlugin({
title: 'Output Management'
})
],
module: {
rules: [
{
test: /.css$/,
use: ['style-loader', 'css-loader']
},
{
test: /\.(png|svg|jpg|gif)$/,
use: ['file-loader']
},{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: ['file-loader']
}
]
}
}

webpack-dev-middleware doesn't hot replace modules

I tried using webpack-dev-middleware as a middleware.
I bundles in memory as it should and serves the JS output file,
but it doesn't hot reload when I save.
any ideas?
You'll want to use https://www.npmjs.com/package/webpack-hot-middleware or something similar.
You should use webpack-hot-middleware. here is a working example. I hope it helps.
for your webpack config (lets call it webpack.config.dev):
const path = require('path');
const webpack = require('webpack');
const distPath = path.resolve(__dirname, '../dist');
const srcPath = path.resolve(__dirname, '../src');
module.exports = {
context: srcPath,
target: 'web',
entry: [
'react-hot-loader/patch',
// activate HMR for React
// bundling the client for webpack-dev-server
// and connect to the provided endpoint
'webpack-hot-middleware/client',
'./client/index.js'
// the entry point of your app
],
output: {
filename: 'app.js',
// the output bundle
path: distPath,
publicPath:'/static/',
// necessary for HMR to know where to load the hot update chunks
pathinfo: true
},
module: {
rules: [
// eslint checking before processed by babel
{test: /\.js$/, enforce: 'pre', loader: 'eslint-loader', exclude: /node_modules/},
// babel
{test: /\.js$/, use: [{loader: 'babel-loader'}], exclude: /node_modules/}
]
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
// enable HMR globally
new webpack.DefinePlugin({ "process.env": { NODE_ENV: '"development"' } })
]
};
For the server (called index.dev.js):
import path from 'path';
import express from 'express';
import React from 'react';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import { renderToString } from 'react-dom/server';
// the above file
import webpackConfig from '../../webpack/webpack.config.dev';
// myown react Html component
import Html from '../server/Html';
const app = express();
app.use(express.static(path.join(__dirname, '..', './public')));
const compiler = webpack(webpackConfig);
app.use(webpackDevMiddleware(compiler, {
quiet: true,
noInfo: true,
publicPath: webpackConfig.output.publicPath,
stats: { colors: true }
}));
app.use(webpackHotMiddleware(compiler));
app.get('*', (req, res) =>
res.status(200).send(`<!doctype html>${renderToString(
<Html />)}`
// This is my own Html react component. You can send a static html file here as well.
)
);
app.listen(3000, (err) => {
if (err) {
console.error(err);
return;
}
console.info('Demo app listening on port 3000');
});
At the end I call it using babel-watch:
"scripts": {
"start:dev": "rm -f ./dist/* && ./node_modules/.bin/babel-watch ./src/server/index.dev.js -w ./src/server",
},

Categories