NODE.JS: Why can't I get live reload with web pack? - node.js

IM SO FRUSTRATED RIGHT NOW, ive spent a whole day trying to get webpack to work, but every tutorial or documentation is terrible..it shouldnt be this hard..whats the point of these packages if they actually make you spend more time trying to configure them then saving time.
I just want the live reload to work. I've tried the inline method, iframe, hot module, the middleware with express. None of it works...Im using Node.js on atom, with safari browser.
I want it to work with express.
Can someone point me to a good tutorial...or explain step by step very simply..
Need help. please. no one every replies on these things! Thank you
GITHUB REPO LINK
webpack.config.js
const nodeExternals = require('webpack-node-externals');
module.exports =
{
entry: './app.js',
target: 'node',
externals: [nodeExternals()],
output: {
path: __dirname + '/dist',
filename: 'app.bundle.js',
},
devServer: {
port: 8000,
open: true,
inline: true
},
module: {
loaders: [
{
loader: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/
}
]
}
}
package.json
{
"name": "clinic8beauty",
"version": "1.0.0",
"description": "",
"main": "app.js",
"scripts": {
"b": "webpack",
"s": "webpack-dev-server",
"test": "echo \"Error: no test specified\" && exit 1"
},
"babel": {
"presets": [
"es2015"
]
},
"author": "Kosta Pontidas",
"license": "ISC",
"dependencies": {
"body-parser": "^1.17.1",
"events": "^1.1.1",
"express": "^4.15.2",
"jquery": "^3.2.1",
"pug": "^2.0.0-beta.12",
"twilio": "^2.11.1",
"validator": "^7.0.0"
},
"devDependencies": {
"babel-core": "^6.24.1",
"babel-loader": "^7.0.0",
"babel-polyfill": "^6.23.0",
"babel-preset-es2015": "^6.24.1",
"node-sass": "^4.5.2",
"pug-html-loader": "^1.1.4",
"sass-loader": "^6.0.3",
"webpack": "^2.4.1",
"webpack-dev-server": "^2.4.4",
"webpack-hot-middleware": "^2.18.0",
"webpack-node-externals": "^1.5.4"
}
}
app.js requires
const express = require('express'),
app = express(),
events = require('events'),
eventEmitter = new events.EventEmitter(),
bodyParser = require('body-parser'),
validator = require('validator'),
client = require('twilio')('AC3cdbdc7ecb720d5521f41243450343e8',
'8f76c52d839dc25aa17ddc72b3b9d781');

You have target node in your config change it to web or remove it as default is web. It should fix your problem.

Can you try the following?
const nodeExternals = require('webpack-node-externals');
const path = require('webpack'); // <== added
module.exports =
{
entry: './app.js',
// target: 'node', <== deleted
externals: [nodeExternals()],
output: {
path: path.resolve(__dirname, 'dist'), //<== added
filename: 'app.bundle.js'
},
devServer: {
port: 8000,
open: true,
inline: true,
contentBase: [path.resolve(__dirname, 'dist')/* add other directories if needed */]
},
module: {
loaders: [
{
loader: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/
}
]
}
}
And run webpack-dev-server --progress instead of just webpack to start the server

Why not use nodemon globally and webpack to compile

Related

How to configure webpack to deploy react application on heroku?

I have created a react application from scratch and I'm trying to deploy it on heroku but unfortunately I faced a lot of errors, however I came to the point where I need to add a start script to my package.json file according to the logs of heroku :
npm ERR! Missing script: "start"
I don't know what content to add to my start script command in the package.json because I don't know if it takes additional webpack configuration or not, here is the file :
{
"name": "APPNAME",
"version": "1.0.0",
"description": " web application, etc..",
"main": "index.js",
"scripts": {
"dev": "webpack-dev-server --mode development",
"build" : "webpack --mode production"
},
"repository": {
"type": "git",
"url": "gitrepo"
},
"author": "LOUKACH EL-Mehdi",
"license": "ISC",
"bugs": {
"url": "ISSUES"
},
"homepage": "readme",
"devDependencies": {
"#babel/cli": "^7.1.0",
"#babel/core": "^7.1.0",
"#babel/preset-env": "^7.1.0",
"#babel/preset-react": "^7.0.0",
"babel-loader": "^8.0.2",
"css-loader": "^5.2.7",
"style-loader": "^2.0.0",
"webpack": "^4.46.0",
"webpack-cli": "^4.10.0",
"webpack-dev-server": "^4.9.3"
},
"dependencies": {
"aos": "^2.3.4",
"bootstrap": "^5.1.3",
"express": "^4.18.1",
"react": "^18.2.0",
"react-bootstrap": "^2.4.0",
"react-dom": "^18.2.0",
"react-flow-renderer": "^10.3.11"
}
}
I have a webpack.config.js file that allows me to parse the bundle.js file :
const path = require("path");
const webpack = require("webpack");
module.exports = {
entry: "./src/index.js",
mode: "development",
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /(node_modules|bower_components)/,
loader: "babel-loader",
options: { presets: ["#babel/env"] }
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"]
}
]
},
resolve: { extensions: ["*", ".js", ".jsx"] },
output: {
path: path.resolve(__dirname, "dist/"),
publicPath: "/dist/",
filename: "bundle.js"
},
devServer: {
static : {
directory : path.join(__dirname, "public/")
},
port: 3000,
devMiddleware:{
publicPath: "https://localhost:3000/dist/",
},
hot: "only",
},
plugins: [new webpack.HotModuleReplacementPlugin()]
};
P.S : after browsing the internet, I found out about an express file can be added to the root directory of the project, please let me know if this is the way to go to deploy the application on heroku, thank you !

node js webpack Undefined envioronment variable

HHHi,
I'm trying to use the .env file to store the API id and key for the API I'm using and it's not working. My .env file is in the root of my working directory as well as the root of the repository where the .gitignore file is. It looks like this:
API_ID=XXXXXX
API_KEY=XXXXXXXXXXXXXXXXXXXXXXXXXXX
I installed dotenv and in my index.js file in my server directory I call it like this:
const dotenv = require('dotenv');
dotenv.config();
then in my apiCall.js function I try to call the variables from the .env file like this:
const AYLIENTextAPI = require('aylien_textapi');
let textapi = new AYLIENTextAPI({
application_id: process.env.API_ID,
application_key: process.env.API_KEY
});
but the ID and Key are showing up as undefined. What am I doing wrong? I would really appreciate any help.
Thanks,
Mike
UPDATE:
this is my webpack.dev.js file:
const path = require('path')
const webpack = require('webpack')
const HtmlWebPackPlugin = require("html-webpack-plugin")
const { CleanWebpackPlugin } = require('clean-webpack-plugin')
module.exports = {
entry: './src/client/index.js',
output : {
libraryTarget: 'var',
library: 'Client'
},
mode: 'development',
devtool: 'source-map',
stats: 'verbose',
module: {
rules: [
{
test: '/\.js$/',
exclude: /node_modules/,
loader: "babel-loader"
},
{
test: /\.scss$/,
use: [ 'style-loader', 'css-loader', 'sass-loader' ]
}
]
},
plugins: [
new HtmlWebPackPlugin({
template: "./src/client/views/index.html",
filename: "./index.html",
}),
new CleanWebpackPlugin({
// Simulate the removal of files
dry: true,
// Write Logs to Console
verbose: true,
// Automatically remove all unused webpack assets on rebuild
cleanStaleWebpackAssets: true,
protectWebpackAssets: false
})
]
}
this is my package.json file:
{
"name": "example-project",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node src/server/index.js",
"build-prod": "webpack --config webpack.prod.js",
"build-dev": "webpack --config webpack.dev.js"
},
"keywords": [],
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"aylien_textapi": "^0.7.0",
"dotenv": "^8.2.0",
"express": "^4.17.1",
"webpack": "^4.41.6",
"webpack-cli": "^3.3.11"
},
"devDependencies": {
"#babel/core": "^7.8.4",
"#babel/preset-env": "^7.8.4",
"babel-loader": "^8.0.6",
"clean-webpack-plugin": "^3.0.0",
"css-loader": "^3.4.2",
"html-webpack-plugin": "^3.2.0",
"mini-css-extract-plugin": "^0.9.0",
"node-sass": "^4.13.1",
"optimize-css-assets-webpack-plugin": "^5.0.3",
"sass-loader": "^8.0.2",
"style-loader": "^1.1.3",
"terser-webpack-plugin": "^2.3.5",
"webpack-dev-server": "^3.10.3",
"workbox-webpack-plugin": "^5.0.0"
}
}
figured it out. I can only access the environment variables on the server side.

How to build (Webpack) the Node Js project using PUG Engine?

I am stuck to build the node js project using webpack and I am using pug engine for front end.
My Project Structure:
bin
controller
- csv.controller.js
public
- stylesheets
- javascript
- images
routes
- csv.route.js
- index.route.js
views
- layouts
-- layout.pug
-index.pug
app.js
Package.json File
{
"name": "csv",
"version": "0.0.0",
"private": true,
"scripts": {
"build": "webpack --mode=production",
"build:dev": "webpack --mode=development",
"start":"nodemon ./app.js",
"start:dev": "webpack-dev-server --mode=development"
},
"dependencies": {
"body-parser": "^1.19.0",
"compression": "^1.7.4",
"cookie-parser": "~1.4.4",
"csv-parser": "^2.3.1",
"csv-writer": "^1.5.0",
"debug": "~2.6.9",
"express": "^4.17.1",
"express-fileupload": "^1.1.6-alpha.5",
"fast-csv": "^3.4.0",
"http-errors": "~1.6.3",
"morgan": "^1.9.1",
"multer": "^1.4.2",
"npm-check-updates": "^3.1.23",
"request": "^2.88.0"
},
"devDependencies": {
"#babel/core": "^7.6.2",
"#babel/preset-env": "^7.6.2",
"babel-loader": "^8.0.6",
"clean-webpack-plugin": "^3.0.0",
"css-loader": "^3.2.0",
"extract-text-webpack-plugin": "^3.0.2",
"file-loader": "^4.2.0",
"html-webpack-plugin": "^3.2.0",
"mini-css-extract-plugin": "^0.8.0",
"pug": "^2.0.4",
"pug-loader": "^2.4.0",
"style-loader": "^1.0.0",
"webpack": "^4.40.2",
"webpack-cli": "^3.3.9",
"webpack-dev-server": "^3.8.1",
"webpack-merge": "^4.2.2"
}
}
Actually what I want, after build, A dist folder contain a build.js or whatever its name and all public folder assets in the same directory. I tried with some below codes to build the project.
Webpack.config.js
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const ExtractTextPlugin = require("extract-text-webpack-plugin");
const config = {
entry: {
app: "./app.js"
},
target: "node",
output: {
path: path.resolve(__dirname, "dist"),
filename: "[name].bundle.js"
},
devServer: {
port: 3000
},
plugins: [
new HtmlWebpackPlugin({
template: "./views/index.pug"
})
],
module: {
rules: [
{
test: /\.pug$/,
use: ["pug-loader"]
},
{
test: /\.css$/,
use: ["style-loader", "css-loader"]
},
{
test: /\.(png|svg|jpg|gif)$/,
use: ["file-loader"]
},
{
test: [/.js$/],
exclude: /(node_modules)/,
use: {
loader: "babel-loader",
options: {
presets: ["#babel/preset-env"]
}
}
},
{
test: /\.css$/,
use: ExtractTextPlugin.extract({
fallback: "style-loader",
use: "css-loader"
})
}
]
}
};
module.exports = (env, argv) => {
if (argv.mode === "development") {
}
if (argv.mode === "production") {
}
return config;
};
I know this question is old, but just in case somebody is looking for an answer.
You need another Webpack config for app.js, which is express entry point.
Call it webpack.server.js or webpack.server.config.js or whatever convenient. Make sure to include webpack-node-externals:
https://www.npmjs.com/package/webpack-node-externals
It may look something like this:
//webpack.server.js
const path = require('path');
const webpack = require('webpack');
const nodeExternals = require('webpack-node-externals');
module.exports = {
return ({
entry: {
app: ./src/server/app.js,
},
output: {
path: path.join(__dirname, 'dist'),
publicPath: '/',
filename: '[name].js',
},
target: 'node',
node: {
__dirname: false,
__filename: false,
},
externals: [nodeExternals()],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: 'babel-loader',
},
},
],
},
});
};
Also use webpack-dev-middleware in your app.js.
See the below link:
https://webpack.js.org/guides/development/
In package.json include a script that looks something like this:
"server:dev": "webpack --config webpack.config.js && webpack --mode development --config webpack.server.js && node ./dist/app.js",
In your webpack.config.js make the entry point the js file that imports your front-end assets..
That is your stylesheets and any other js codes..
Not sure what css framework you are using.
But, I am using tailwindcss and I have a js entry point file that imports tailwindcss and my other js codes.
So essentially you may need two webpack config files one for the front-end and one for the express server.
Hope I am making sense.

npx webpack Unexpected token :

I am trying to use Webpack for the first time with Node and Babel (this is my first time using Babel as well) on Windows 10. I think I have everything configured properly, but it's giving me a cryptic error:
The same thing happens if I do npx webpack --exec bable-node.
In everything I've read about this, it gives a line number. I'm not sure what's the issue.
I have all of the files I thought were related to Node in a folder called "node", and all the other files in a folder called "src". I don't know if this is causing the issue. Here is the folder structure:
/node
/config
/node_modules
.babelrc
master-updated.sh
package-lock.json
package.json
server2.js
webpack.config.js
/src
/model (this is has a bunch of js files, but I removed the references to them for now)
/public
/html
/srcipts
/stylesheets
/css
/scss
/vue
.gitignore
master-updated.sh is a shell script for responding to a GitHub webhook.
Here is the beginning of server2.js:
'use strict';
process.env.NODE_CONFIG_DIR = './node/config';
const config = require('config'),
babel = require('babel-core'),
ejs = require('ejs'),
util = require('util'),
express = require('express'),
bodyParser = require('body-parser'),
cors = require('cors'),
moment = require('moment'),
plaid = require('plaid'),
mariadb = require('mariadb'),
fs = require('fs'),
http = require('http'),
https = require('https'),
session = require('express-session'),
exec = require('child_process').exec;
const GOOGLE_AUTH_CLIENT_ID = '<REDACTED>';
const { OAuth2Client } = require('google-auth-library');
const googleAuthClient = new OAuth2Client(GOOGLE_AUTH_CLIENT_ID);
const APP_PORT = config.APP_PORT;
Here is my webpack.config.js file:
module.exports = {
target: 'node',
entry: {
app: ['./server2.js']
},
output: {
filename: 'server.js',
path: path.resolve(__dirname, 'test')
},
module: {
loaders: [
test: '/\.js$/',
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ["#babel/preset-env"]
}
]
}
}
Here is .babelrc:
{"presets": ["#babel/preset-env"]}
And here is package.json:
{
"name": "sage-savings",
"version": "0.0.1",
"description": "An app for easy budgeting.",
"main": "server2.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"build": "webpack --config node/webpack.config.js",
"start": "node node/server2.js"
},
"author": "Dakota Dalton",
"repository": "https://github.com/1silvertiger/Sage",
"license": "ISC",
"dependencies": {
"#types/express": "^4.16.1",
"aws-sdk": "^2.397.0",
"body-parser": "^1.18.3",
"config": "^3.0.1",
"cors": "^2.8.5",
"ejs": "^2.5.9",
"express": "4.16.x",
"express-session": "^1.15.6",
"google-auth-library": "^3.0.1",
"mariadb": "^2.0.3",
"moment": "^2.22.2",
"mysql": "^2.16.0",
"plaid": "2.x.x"
},
"devDependencies": {
"#babel/core": "^7.3.4",
"#babel/preset-env": "^7.3.4",
"ajv": "^6.10.0",
"babel-core": "^6.26.3",
"babel-loader": "^8.0.5",
"babel-preset-env": "^1.7.0",
"typescript": "^3.3.3333",
"webpack": "^4.29.6",
"webpack-cli": "^3.2.3"
}
}
These syntax problems are easily identified if you use an IDE which has syntax highlighting, for example VS Code. All I did was copy your config into a file and load it into VS Code.
You are incorrectly closing the regular expression used for exclude:
exclude: /node_modules\,
You must use a forward slash instead of a back slash:
exclude: /node_modules/
You also need to wrap your loader in an object literal:
loaders: [
{ // <= wrap in object literal
test: '/\.js$/',
loader: 'babel-loader',
exclude: /node_modules/,
query: {
presets: ["#babel/preset-env"]
}
}
]

Electron and Webpack ENOENT: no such file or directory, open '/path.txt'

I am a beginner trying to use Electron (formerly Atom) and Reactjs bundled with Webpack. Everything was working fine until I tried to use Electron's remote module to access the mainWindow in my React components.
Trying to import this module, I get the infamous error:
Uncaught Error: ENOENT: no such file or directory, open '/path.txt'
I've tried reinstalling electron and I've checked node_modules/electron, and found that path.txt is there.
Here is my webpack.config.js:
var webpack = require('webpack');
module.exports = {
context: __dirname,
entry: {
app: ['webpack/hot/dev-server', './src/App.jsx'],
},
target: 'node',
output: {
path: './public/built',
filename: 'bundle.js',
publicPath: 'http://localhost:8080/built/'
},
devServer: {
contentBase: './public',
publicPath: 'http://localhost:8080/built/'
},
module: {
loaders: [
{
test: /\.jsx?$/,
loader: 'babel-loader',
exclude: /node_modules/,
include: /src/,
query: {
presets: ['es2015', 'react']
}
},
{
test: /\.(png|jpg)$/,
loader: 'file-loader?name=[path][name].[hash].[ext]'
},
{
test: /\.css$/,
loader: 'style-loader!css-loader'
}
]
},
plugins: [
new webpack.HotModuleReplacementPlugin()
]
}
And here is my package.json:
{
"name": "app",
"version": "0.1.0",
"main": "main.js",
"description": "description",
"license": "UNLICENSED",
"repository": {
"type": "git",
"url": "https://github.com"
},
"scripts": {
"start": "./node_modules/.bin/electron .",
"watch": "./node_modules/.bin/webpack-dev-server"
},
"dependencies": {
"electron": "^1.3.5",
"radium": "^0.17.1",
"react": "^15.0.1",
"react-dom": "^15.0.1"
},
"devDependencies": {
"babel": "^6.5.2",
"babel-core": "^6.7.7",
"babel-loader": "^6.2.4",
"babel-preset-es2015": "^6.6.0",
"babel-preset-react": "^6.5.0",
"css-loader": "^0.24.0",
"file-loader": "^0.9.0",
"style-loader": "^0.13.1",
"webpack": "^1.13.0",
"webpack-dev-server": "^1.14.1"
}
}
I suspect that it may have something to do with the start script in package.json as the path.txt is not in the same directory as node_modules/.bin/electron. However, I haven't figured out how to solve this.
in case it's not to late, you simply need to replace your "node" target with "electron-renderer" in your webpack.config.js
Just run command like below
cd node_modules/electron && node install.js
It will create path.txt file
For Mac the file contains like below
dist/Electron.app/Contents/MacOS/Electron

Resources