Webpack-Dev-Server With Gulp Not Reloading After Code Change - javascript

im new to webpack and im trying to get it to work with gulp. i am using the guide found at the following link, but it doesnt seem to be working:
https://webpack.github.io/docs/usage-with-gulp.html
can anyone tell me which part of my configuration is wrong?
gulpfile.js
import gulp from 'gulp';
import webpack from 'webpack';
import gutil from "gulp-util";
import WebpackDevServer from "webpack-dev-server";
import webpackConfig from './webpack.config';
gulp.task("dev-server", function(callback) {
// Start a webpack-dev-server
var compiler = webpack(webpackConfig);
new WebpackDevServer(compiler, {
}).listen(4000, "localhost", function(err) {
if(err) throw new gutil.PluginError("webpack-dev-server", err);
// Server listening
gutil.log("[webpack-dev-server]", "http://localhost:4000/webpack-dev-server/index.html");
// keep the server alive or continue?
// callback();
});
});
webpack.config.js
const path = require("path");
module.exports = {
watch: true,
entry: {
app: __dirname+'/dev/index.js'
},
output: {
path: path.join(__dirname, "dist"),
filename: '[name].js'
},
module: {
loaders: [
{test: /\.js$/, loaders: ['babel']},
{test: /\.scss$/, loaders: ["style", "css", "sass"]}
]
}
}

There are differences between the Node.js API and the CLI for webpack dev server. You are using the Node.js API so should see here: https://webpack.js.org/guides/hot-module-replacement/#via-the-node-js-api
Try something along these lines inside the gulp task defining function:
// Add entry points for '/webpack-dev-server/client/index.js' necessary for live reloading
WebpackDevServer.addDevServerEntrypoints(webpackConfig, { ... dev-server-options ...});
// Start a webpack-dev-server
var compiler = webpack(webpackConfig);
new WebpackDevServer(compiler, {
}).listen(4000, "localhost", function(err) {
if(err) throw new gutil.PluginError("webpack-dev-server", err);
// Server listening
gutil.log("[webpack-dev-server]", "http://localhost:4000/webpack-dev-server/index.html");
// keep the server alive or continue?
// callback();
});
Essentially add the one line WebpackDevServer.addDevServerEntrypoints(webpackConfig, { ... dev-server-options ...}); to the beginning of your task function. This will add "/webpack-dev-server/client/index.js" as an entry to your webpack config and is needed for live reloading.

Related

Using environment variables in split webpack configuration

I'm reading the webpack docs on environment variables. In order to use the env variable they convert the module.exports into a function.
How do I perform this "conversion into a function" if my module.exports object is split across two files:
webpack.common.js:
const path = require("path");
const Dotenv = require("dotenv-webpack");
//Other stuff.
module.exports = {
entry: {
app: "./src/app.tsx",
},
module: {
rules: loaders,
},
resolve: {
extensions: [".tsx", ".ts", ".js", ".jsx"],
},
output: {
filename: "main.bundle.js",
path: path.resolve(path.resolve(), "../dist"),
},
plugins: [new Dotenv({ path: "../backend/.env.development" })], //Wish to be able to change the path depending on 'env'
};
webpack.dev.js:
const path = require("path");
const { merge } = require("webpack-merge");
const common = require("./webpack.common.js");
const fs = require("fs");
module.exports = merge(common, {
devtool: "inline-source-map",
mode: "development",
devServer: {
static: {
directory: path.join(path.resolve(), "../dist"),
},
port: 3000,
http2: true,
https: {
key: fs.readFileSync("../pathtokey.pem"),
cert: fs.readFileSync("../pathtocert.pem"),
},
},
});
If I simply convert both objects in both files into functions, it errors out.
The reason for my attempt is that I'm trying to gain access to a webpack environment variable env so that I may tell dotenv-webpack which .env file to refer to (either "development" or "production", in webpack.common.js). I'm also new to this so any tips are appreciated.

MainTemplate.hooks.startup has been removed (use RuntimeGlobals.startup instead)

I am watching a video that teaches me to join to react with the back-end, everything is fine after putting the middlwares I always get an error, and I tried to solve it but I could not
Error:
C:\Users\Danjos02\Desktop\Cursos\React-Curso\react-node-project\node_modules\webpack\lib\MainTemplate.js:100
throw new Error(
^
Error: MainTemplate.hooks.startup has been removed (use RuntimeGlobals.startup instead)
at Object.tap (C:\Users\Danjos02\Desktop\Cursos\React-Curso\react-node-project\node_modules\webpack\lib\MainTemplate.js:100:12)
at LiveReloadPlugin.applyCompilation (C:\Users\Danjos02\Desktop\Cursos\React-Curso\react-node-project\node_modules\webpack-livereload-plugin\index.js:164:42)
at Hook.eval (eval at create (C:\Users\Danjos02\Desktop\Cursos\React-Curso\react-node-project\node_modules\webpack\node_modules\tapable\lib\HookCodeFactory.js:19:10), <anonymous>:100:1)
at Hook.CALL_DELEGATE [as _call] (C:\Users\Danjos02\Desktop\Cursos\React-Curso\react-node-project\node_modules\webpack\node_modules\tapable\lib\Hook.js:14:14)
at Compiler.newCompilation (C:\Users\Danjos02\Desktop\Cursos\React-Curso\react-node-project\node_modules\webpack\lib\Compiler.js:993:26)
at C:\Users\Danjos02\Desktop\Cursos\React-Curso\react-node-project\node_modules\webpack\lib\Compiler.js:1035:29
at Hook.eval [as callAsync] (eval at create (C:\Users\Danjos02\Desktop\Cursos\React-Curso\react-node-project\node_modules\webpack\node_modules\tapable\lib\HookCodeFactory.js:33:10), <anonymous>:6:1)
at Hook.CALL_ASYNC_DELEGATE [as _callAsync] (C:\Users\Danjos02\Desktop\Cursos\React-Curso\react-node-project\node_modules\webpack\node_modules\tapable\lib\Hook.js:18:14)
at Compiler.compile (C:\Users\Danjos02\Desktop\Cursos\React-Curso\react-node-project\node_modules\webpack\lib\Compiler.js:1030:28)
at C:\Users\Danjos02\Desktop\Cursos\React-Curso\react-node-project\node_modules\webpack\lib\Watching.js:112:19
I got the original webpack of the video but still the error is not solved, so I doubt that it is something of the code, but still I can not solve since I am new to this topic
Webpack.config.js code
import webpack from 'webpack';
import htmlWebpackPlugin from 'html-webpack-plugin';
import LiveReloadPlugin from 'webpack-livereload-plugin';
export default {
entry: './src/client/index.js',
output: {
path: '/',
filename: 'bundle.js'
},
module: {
rules: [
{
use: 'babel-loader',
test: /\.js$/,
exclude: /node_modules/
},
{
use: ['style-loader', 'css-loader'],
test: /\.css$/
},
{
test: /\.scss$/,
use: [
{
loader: 'style-loader'
},
{
loader: 'css-loader', options: {
sourceMap: true
}
},
{
loader: 'sass-loader', options: {
sourceMap: true
}
}
]
}
]
},
plugins: [
new htmlWebpackPlugin({
template: 'src/client/index.html'
}),
new LiveReloadPlugin()
]
}
Server.js
import express from 'express';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackConfig from '../webpack.config';
// initializing packages
const app = express();
// settings
app.set('port', process.env.PORT || 3000);
// middlwares
app.use(webpackDevMiddleware(webpack(webpackConfig)));
// routes
app.get('/', (req, res) => {
res.send('Hello World');
});
app.get('/api', (req, res) => {
res.json({api: 'works!'});
});
// starting the server
app.listen(app.get('port'), () => {
console.log(`Server on port ${app.get('port')}`);
});
I have read and apparently the error is from the webpack-livereload-plugin, but I could not detect the error
If anyone knows why this error occurs please help me

I'm trying to link Node.js+Webpack+MySQL, but it's stuck in fs module. Help me

I tried to run the program by linking MySQL and Node.js, but fs cannot be loaded due to the following errors.
Module not found: Error: Can't resolve 'fs'
By the way, adding target:'node', causes a global is not defined error.
and add node {fs:'empty'}, causes a createConnection is not a function error.
What should I do now
webpack.config.js
const path = require('path');
module.exports = (env, argv) => {
return {
mode: 'production',
entry: {
index : path.join(__dirname, 'src' ,'index.ts'),
},
output: {
path: path.join(__dirname, 'www'),
filename: 'game.js',
library: 'game',
libraryTarget: 'umd'
},
resolve: {
extensions: ['.ts', '.js'],
modules: [
path.resolve(__dirname, 'src'),"node_modules"
]
},
module: {
rules: [
{
test : /\.ts$/,
use: [{ loader: 'ts-loader'}]
}
]
}
}
};
mysql function
function get_connection():void {
console.log("mysql : ",mysql)
console.log("mysql.createConnection", mysql.createConnection)
connection = mysql.createConnection({
host: "host",
user: "user",
password: "pass",
database: "database"
}).then(conn => {
console.log('promise-mysql createConnection.');
connection = conn;
return conn;
}).catch(err => {
console.log("promise fail:",err)
})
}
As you're keen to use webpack to bundle for node server code, you shouldn't bundle node_nodules by using this helper webpack-node-externals. So try more with these options:
var nodeExternals = require('webpack-node-externals')
target: 'node',
externals: [
nodeExternals(),
],
node: {
fs: "empty",
}

problems with vue-cli for production

I am currently working on a vue-cli app,but I am having problems to run the app on production locally. After finishing everything on the dev environment I used the following command to build my production version of the app.
npm run build
the following is my config/prod.env.js file:
'use strict'
module.exports = {
NODE_ENV: '"production"'
}
config/index.js file:
'use strict'
// Template version: 1.3.1
// see http://vuejs-templates.github.io/webpack for documentation.
const path = require('path')
module.exports = {
dev: {
// Paths
assetsSubDirectory: 'static',
assetsPublicPath: '/',
proxyTable: {},
// Various Dev Server settings
host: 'localhost', // can be overwritten by process.env.HOST
port: 8080, // can be overwritten by process.env.PORT, if port is in use, a free one will be determined
autoOpenBrowser: false,
errorOverlay: true,
notifyOnErrors: true,
poll: false, // https://webpack.js.org/configuration/dev-server/#devserver-watchoptions-
/**
* Source Maps
*/
// https://webpack.js.org/configuration/devtool/#development
devtool: 'cheap-module-eval-source-map',
// If you have problems debugging vue-files in devtools,
// set this to false - it *may* help
// https://vue-loader.vuejs.org/en/options.html#cachebusting
cacheBusting: true,
cssSourceMap: true
},
build: {
// Template for index.html
index: path.resolve(__dirname, '../dist/index.html'),
// Paths
assetsRoot: path.resolve(__dirname, '../dist'),
assetsSubDirectory: 'static',
assetsPublicPath: '/',
/**
* Source Maps
*/
productionSourceMap: true,
// https://webpack.js.org/configuration/devtool/#production
devtool: '#source-map',
// Gzip off by default as many popular static hosts such as
// Surge or Netlify already gzip all static assets for you.
// Before setting to `true`, make sure to:
// npm install --save-dev compression-webpack-plugin
productionGzip: false,
productionGzipExtensions: ['js', 'css'],
// Run the build command with an extra argument to
// View the bundle analyzer report after build finishes:
// `npm run build --report`
// Set to `true` or `false` to always turn it on or off
bundleAnalyzerReport: process.env.npm_config_report
}
}
config/dev.env.js:
'use strict'
const merge = require('webpack-merge')
const prodEnv = require('./prod.env')
module.exports = merge(prodEnv, {
NODE_ENV: '"development"'
})
build/build.js:
'use strict'
require('./check-versions')()
process.env.NODE_ENV = 'production'
const ora = require('ora')
const rm = require('rimraf')
const path = require('path')
const chalk = require('chalk')
const webpack = require('webpack')
const config = require('../config')
const webpackConfig = require('./webpack.prod.conf')
const spinner = ora('building for production...')
spinner.start()
rm(path.join(config.build.assetsRoot, config.build.assetsSubDirectory), err => {
if (err) throw err
webpack(webpackConfig, (err, stats) => {
spinner.stop()
if (err) throw err
process.stdout.write(stats.toString({
colors: true,
modules: false,
children: false, // if you are using ts-loader, setting this to true will make typescript errors show up during build
chunks: false,
chunkModules: false
}) + '\n\n')
if (stats.hasErrors()) {
console.log(chalk.red(' Build failed with errors.\n'))
process.exit(1)
}
console.log(chalk.cyan(' Build complete.\n'))
console.log(chalk.yellow(
' Tip: built files are meant to be served over an HTTP server.\n' +
' Opening index.html over file:// won\'t work.\n'
))
})
})
it created a dist folder in which I initialised a package.json and installed express on it:
package.json:
{
"name": "project_gorilla_production",
"version": "0.0.0",
"description": "THe production version for project gorilla",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"ProjectGorilla",
"BkChatLDN",
"zezemills"
],
"author": "Christopher Salay",
"license": "ISC",
"dependencies": {
"express": "^4.16.4"
}
}
my server.js file:
const express = require('express');
const app = express();
const path = require('path');
app.get('/', function(req, res) {
res.sendFile(path.join(__dirname, 'index.html'));
});
app.listen(process.env.PORT || 8000, function(){
console.log('Your node js server is running');
})
index.html file:
<!DOCTYPE html><html><head><meta charset=utf-8><meta name=viewport content="width=device-width,initial-scale=1"><title>project_gorilla</title><script src=https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.1.1/socket.io.js></script><link href=/static/css/app.b2785d7282208bedd7a467d4d7584204.css rel=stylesheet></head><body><div id=app></div><script type=text/javascript src=/static/js/manifest.2ae2e69a05c33dfc65f8.js></script><script type=text/javascript src=/static/js/vendor.91dc1c7d90da0f3312fd.js></script><script type=text/javascript src=/static/js/app.75194bcb7c3977e313be.js></script></body></html>
I get the following error when I run node server.js:
Refused to apply style from 'http://localhost:8000/static/css/app.b2785d7282208bedd7a467d4d7584204.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled.
and a lot of my files such as the manifest, the vendor and the app js files gives of a 404 error.

dotenv not working with serverless/webpack

EDIT: If I log out dotenv.config() I get an error of : Error: ENOENT: no such file or directory, open '/Users/myPathToApplication/.webpack/test/.env'
I am bundling my serverless handler in order to use es6/es7 code. I have some env variables that I am trying to use as well. The problem is it seems that dotenv is not working when I bundle the handler.
For example one of the utils I am using is connecting mongoose to my application. In here I store the DB_URI as an env variable. import envdotjs from 'envdotjs';
import mongoose from 'mongoose';
mongoose.Promise = global.Promise;
require('dotenv').config();
let isConnected;
const connectToDatabase = () => {
if (isConnected) {
console.log('=> using existing database connection');
return Promise.resolve();
}
console.log('=> using new database connection');
return mongoose.connect(process.env.DB_URI).then(db => {
isConnected = db.connections[0].readyState;
});
};
module.exports = {
connectToDatabase
};
However the DB_URI is undefined and the code breaks.
Here is my webpack:
const slsw = require('serverless-webpack');
const nodeExternals = require('webpack-node-externals');
module.exports = {
entry: slsw.lib.entries,
target: 'node',
devtool: 'source-map',
externals: [nodeExternals()],
mode: slsw.lib.webpack.isLocal ? 'development' : 'production',
module: {
rules: [
{
test: /\.js$/,
loader: 'babel-loader',
include: __dirname,
exclude: /node_modules/
}
]
}
};
I am running this in order to use es6/7 on serverless handler which is working just fine. But the env variables are breaking. I also tried using a module called envdotjs and got the same results that the env variables are undefined so I don't think this is a problem with dotenv.
I found a package dotenv-webpack also recommended by #apokryfos. Just require it in const Dotenv = require('dotenv-webpack') and include it in the webpack.config.js.
module.exports = {
...
plugins: [new Dotenv()]
}
Just include your .env in the root with your webpack.config.js and you can declare your process.env. anywhere you need to with no other configuration.

Categories

Resources