webpack-dev-server does not watch for my file changes - npm

When I change my files while webpack-dev-server is running, the bundle's files are not updated.
Here are my webpack.config.js and package.json files, as you can see from my npm script, I've solved running webpack watch and webpack-dev-server in the same command (npm run watch & webpack-dev-server --content-base ./ --port 9966):
webpack.config.js:
'use strict';
var ReactStylePlugin = require('react-style-webpack-plugin');
var ExtractTextPlugin = require('extract-text-webpack-plugin');
var webpack = require('webpack');
module.exports = {
devtool: 'sourcemap',
entry: ['./js/main.js'],
output: {
filename: 'bundle.js',
path: __dirname + '/assets',
publicPath: __dirname + '/'
},
module: {
loaders: [
{
test: /\.js$/,
loaders: [
ReactStylePlugin.loader(),
'jsx-loader?harmony'
]
},
{
test: /\.css$/,
loader: ExtractTextPlugin.extract('css-loader')
}
]
},
plugins: [
new ReactStylePlugin('bundle.css'),
new webpack.DefinePlugin({
'process.env': {
// To enable production mode:
//NODE_ENV: JSON.stringify('production')
}
})
]
}
package.json:
{
"name": "reactTest",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"watch": "webpack --watch",
"build": "webpack",
"web": "npm run watch & webpack-dev-server --content-base ./ --port 9966"
},
"author": "",
"license": "ISC",
"devDependencies": {
"css-loader": "^0.10.1",
"extract-text-webpack-plugin": "^0.3.8",
"jsx-loader": "^0.13.1",
"react-style-webpack-plugin": "^0.4.0",
"style-loader": "^0.10.2",
"url-loader": "^0.5.5",
"webpack": "^1.8.5",
"webpack-dev-server": "^1.8.0"
},
"dependencies": {
"react": "^0.13.1",
"react-style": "^0.5.3"
}
}
my directory structure is:
assets
bundle.css
bundle.css.map
bundle.js
bundle.js.map
js
AppActions.js
Profile.css.js
ProfileList.js
main.js
AppConstants.js
AppStore.js
Profile.js
ResultPage.js
package.json
index.html
node_modules
webpack.config.js
every file inside assets directory is generated by webpack

In order to get webpack to watch my file changes (Ubuntu 14.04), I had to increase the number of watchers (I had increased the number before, but it was still too low):
echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p
Source in the official docs: https://webpack.github.io/docs/troubleshooting.html#not-enough-watchers
I first suspected the cause to be fsevents which doesn't work on Ubuntu, but this apparently wasn't the case.
Furthermore, because now the watching and re-compiling worked, but the automatic browser refresh part didn't work, I added the --inline param to the answer of #deowk which enables the "inline mode":
webpack-dev-server --content-base ./ --port 9966 --hot --inline
Quote from the official docs: "The easiest way to use Hot Module Replacement with the webpack-dev-server is to use the inline mode."
Source: https://webpack.github.io/docs/webpack-dev-server.html#hot-module-replacement

you need to run webpack-dev-server with the --hot flag:
webpack-dev-server --content-base ./ --port 9966 --hot
Then you can access the hot-loading version localhost:9966/webpack-dev-server/
You don't need to run watch as well.
update:
This entry in your webpack config must change:
entry: ['./js/main.js'], --> entry: ['webpack/hot/dev-server' , './js/main.js']
Change your publicPath entry:
publicPath: '/assets/'

#funkybunky identified the right problem but (IMHO) fixed it the wrong way. At least in my case, webpack was trying to watch every file it used, including a deep chain of thousands of files of dependencies pulled from npm. I added this to my config, per the docs:
devServer: {
watchOptions: {
ignored: /node_modules/
}
}
Of course you legitimately could have thousands of files that might need to be watched, in which case go ahead and raise the limit, but you're probably better off ignoring vendor libraries that aren't likely to change.

I'll put this here just in case it helps anyone. My problem was the same, but caused by inconsistent capitalization of directory names and webpack alias declaration.
I had a WebGL directory which i referenced in my aliases as webgl, and unfortunately this worked for the build, but didn't work for code watching.

In my case, the error was caused by an empty space in the directory name, by changing "Repository Name" by "RepositoryName", everything worked fine !

Figured I'd post my solution as well. I had the same problem getting Flutter apps to run on OS X due to my hard drive setup.
The gist is if your project folder is in a symlinked folder, detecting the file changes may not work on OS X. Previously, we were on Webpack 3.X, I believe, and live reload/refresh worked fine in the original folder. However, after upgrading to the latest Webpack (^5.75.0) and Webpack Dev Server (^4.11.1), the hot-reloading no longer worked for me.
My original project folder was:
/Users/blakemiller/h/somefolder/v2/my-widget
The "/h" there is a symlink to: /System/Volumes/Data/projects/home/web/
I'm not sure what happened when I upgraded OS X at some point, but the upgrade changed the folders in a way that I don't really understand.
Putting the folder here instead, fixed the issue for me (no symlink):
/Users/blakemiller/my-widget
I doubt this will work for many people, as my setup is probably pretty specific, but maybe it will help someone else save 5 hours down the road...

Related

Failed to load plugin 'react' declared in '.eslintrc.json': Cannot find module 'eslint-plugin-react'

When run locally, it seems to work fine but crashes when its on pipeline
EDIT: After removing npx, it produces a different error:
I have followed the advice of installing the plugin:
npm install eslint-plugin-react#latest --save-dev
But seeps to repeat itself.
Here's my retracted bitbucket-pipelines.yml config:
- step:
name: CI
caches:
- node
script:
- npm install
- npm run lint
- npm run test
eqautes to package.json
"lint": "eslint --ext .js,.ts,.tsx src --ignore-pattern node_modules/",
"test": "jest --verbose --colors --coverage",
Here's my eslint config file:
{
"env": {
"browser": true,
"es6": true,
"jest": true
},
"extends": [
"eslint:recommended",
"plugin:react/recommended",
"airbnb"
],
"globals": {
"Atomics": "readonly",
"SharedArrayBuffer": "readonly"
},
"parser": "#typescript-eslint/parser",
"parserOptions": {
"ecmaFeatures": {
"jsx": true
},
"ecmaVersion": 2018,
"sourceType": "module"
},
"plugins": [
"react",
"#typescript-eslint"
],
"settings": {
"import/resolver": {
"node": {
"extensions": [".js", ".ts", ".tsx"],
"paths": ["src"]
}
}
},
"rules": {
...
}
}
}
An update to Visual Studio Code fixed this for me.
I was unwittingly on a 2 year old version.
Fixed it by removing NODE_ENV in pipelines's .env due to this:
npm install (in package directory, no arguments):
Install the dependencies in the local node_modules folder.
In global mode (ie, with -g or --global appended to the command), it
installs the current package context (ie, the current working
directory) as a global package.
By default, npm install will install all modules listed as
dependencies in package.json.
With the --production flag (or when the NODE_ENV environment variable
is set to production), npm will not install modules listed in
devDependencies.
NOTE: The --production flag has no particular meaning when adding a
dependency to a project.
it happened to to.
tried hard to find the answer.
Apparently, eslint searchs for a roots in the working directory, or something like that, to find the modules to import.
It happens that i've had two apps in my project folder, and only one had the eslintrc.josn.
I fixed to use eslint on the entire project oppening the vs settings.json and add the following:
"eslint.workingDirectories": ["./app1","./app2"...]
if u have more than one app on ur project folder, u should try it

Running Mocha 6 ES6 tests with Babel 7, how to set up?

For a library written in ES6/7, I want to compile (to ES5) the library to a dist/ folder. I also want to run the tests (written in ES6/7) for this lib.
My dev dependencies look like this (package.json):
"devDependencies": {
"#babel/cli": "^7.4.4",
"#babel/core": "^7.4.5",
"#babel/preset-env": "^7.4.5",
"#babel/register": "^7.4.4",
"chai": "^4.2.0",
"mocha": "^6.1.4",
"sinon": "^7.3.2"
},
My build and test scripts looks like this (package.json):
"scripts": {
"test": "mocha --require #babel/register",
"build": "babel src -d dist --presets=#babel/preset-env"
},
Running npm run build works well. The dist/ folder gets populated with transpiled files.
Running npm run test does not seem to work - this is my problem.
> mocha --require #babel/register
/Users/dro/Repos/lib/node_modules/yargs/yargs.js:1163
else throw err
^
ReferenceError: regeneratorRuntime is not defined
Initially I got an import error, which was resolved by adding .babelrc file.
Below is my .babelrc file content.
{
"presets": ["#babel/preset-env"]
}
I was reading about regeneratorRuntime and it got me to this link about babel-polyfill where they explain I shouldn't need that polyfill.
This will emulate a full ES2015+ environment (no < Stage 4 proposals) and is intended to be used in an application rather than a library/tool.
What is needed to set this up properly?
I am not using webpack.
Testing in ES6 with Mocha and Babel 7. Look here: https://dev.to/bnorbertjs/my-nodejs-setup-mocha--chai-babel7-es6-43ei or http://jamesknelson.com/testing-in-es6-with-mocha-and-babel-6/
npm install --save #babel/runtime
npm install --save-dev #babel/plugin-transform-runtime
And, in .babelrc, add:
{
"presets": ["#babel/preset-env"],
"plugins": [
["#babel/transform-runtime"]
]
}
Look at the project documentation:
npm install --save-dev babel-register
In your package.json file make the following changes:
{
"scripts": {
"test": "mocha --require babel-register"
}
}
Some features will require a polyfill:
npm install --save-dev babel-polyfill
{
"scripts": {
"test": "mocha --require babel-polyfill --require babel-register"
}
}
Below steps are for applying Babel transformations & core-js polyfills for your tests file:
💡 All transformations are only done per current environment, so only what is needed to be transpiled/polyfilled, will be. Target environments may be defined from a .browserslist file or as a property in package.json file. (read more here)
Step 1: Install packages:
#babel/core (read why)
#babel/preset-env (read why)
#babel/register (read why)
core-js (read why)
Note that #babel/polyfill exists and uses core-js under the hood. However, it was deprecated in favor of using core-js directly.
Step 2: Create a Babel configuration file babel.config.js
(used to be .babelrc.js or a .json file).
Create this file at the root-level of your code.
The most basic configuration (for just testing and not bundling) would look like this:
module.exports = {
presets: [
['#babel/preset-env', {
"corejs": "3.26",
"useBuiltIns": "usage"
}],
};
corejs - This is the polyfills library and should be specified with the minor version, otherwise x.0 will be used.
It is needed when testing code on rather "old" Node versions, which do not support all of the language methods. This ofc depends on your own usage of such javascript methods. (for example String.prototype.replaceAll).
useBuiltIns - must be set in order for the corejs polyfills to be applied. Read about it in the official docs.
By default, #babel/preset-env will compile your code for the current environment, but you can specify a different environment by setting the "targets" option in the configuration.
Ofc, you can add more presets like #babel/preset-react for example, if your code it written in React, or any other plugins which are specifically needed for your code.
Step 3: Connect mocha to the babel configuration:
In your package.json file
Under the scripts section, simply write something like this:
"test": "mocha \"src/**/*.test.js\""
Create a .mocharc.json file with this content:
{
"exit": true,
"color": true,
"require": ["#babel/register"],
"ignore": "node_modules"
}
This will apply Babel transformations to all of your test files.
If you need need to apply some special global javascript before/to all of your tests, you can add another file to the require setting, for example, fixtures.cjs:
"require": ["#babel/register", "fixtures.cjs"],
fixtures.cjs:
Below example applies a chai (popular alongside Mocha) plugin for testing DOM-related code:
var chai = require('chai'),
chaiDOM = require('chai-dom');
// https://stackoverflow.com/questions/62255953/chai-usechaihttp-once-or-in-every-test-file
// https://mochajs.org/#global-teardown-fixtures
exports.mochaGlobalSetup = function () {
chai.use(chaiDOM);
}
Interesting reads:
Babel vs babel-core vs babel-runtime
How does mocha / babel transpile my test code on the fly?

Webpack Error Reading/Resolving the Entry Module

I'm receiving an error when trying to execute a watch command on webpack and cannot figure out the problem. I have a feeling there's more than one issue, but I'm pretty sure I at least have an idea of one of the problems.
To give a little background, I'm way out of my know-how with all of this and am trying to self-teach how to write a web application with python. I stumbled onto this blog post with a basic example with detailed instructions:
https://codeburst.io/creating-a-full-stack-web-application-with-python-npm-webpack-and-react-8925800503d9
... and getting errors with no context from the source material. They also have a github and youtube video where it was presented, but still no such luck.
I think part of the issue is that their example was written on a MAC which the directory works a little different than windows which is my computer, so in part of the code the directory appears to be off because of that. Here's a screenshot showing the Node.js, the file folder, and the webpack.config.js code:
Here's a screenshot showing the Node.js, the file folder, and the webpack.config.js code:
I noticed that the directory in the example had had '/static/js/index.jsx', but my directory uses the other slash \static\js\index.jsx and the error shows the odd combining as C:\Users...\static/static/js/index.jsx. After learning that \ was an escape code in javascript, I eventually tried the code re-done with the changed slashes.
Here's another screenshot showing the newly run effect ... and it didn't appear to have an effect.
So I'm not sure if what I "fixed" was also an error, but not the current one since it doesn't make sense to me how directory slashes can change... but still no real answers and my knowledge on this was too thin to effectively look it up or learn the nature of the issue.
I have a feeling the actual module either is or may also have some kind of error in the webpack code, but I'm not too sure.
Thanks for any and all time on helping me out,
Matt
Edit: the original post had screenshots of the code and reference to the source material it was copied from, but for reference here are the code segments:
The directory layout is:
| Documents
|--- Python Scripts
|--- fullstacktemplate
|--- fullstack_template
|--- static
|--- js
|--- index.jsx
| node_modules
| index.html
| package.json
| package-lock.json
| webpack.config.js
The node_modules and package-lock.json were auto-created with set up of NPM, Webpack, and/or Babel. Package.json was further edited which will be listed below.
index.jsx is 1 line:
alert("Hello World!");
package.json is as follows:
{
"name": "fullstacktemplate",
"version": "1.0.0",
"description": "fullstack template that will say hello in another language when activated",
"main": "index.jsx",
"scripts": {
"build": "webpack -p --progress --config webpack.config.js",
"dev-build": "webpack --progress -d --config webpack.config.js",
"test": "echo \"Error: no test specified\" && exit 1",
"watch": "webpack --progress -d --config webpack.config.js --watch"
},
"keywords": [
"python",
"react",
"npm",
"webpack"
],
"author": "Matt Lane",
"license": "ISC",
"devDependencies": {
"webpack": "^4.28.2"
}
}
webpack.config.js is as follows:
const webpack = require('webpack');
const config = {
entry: __dirname + '\\js\\index.jsx',
output: {
path: __dirname + '\\dist',
filename: 'bundle.js',
},
resolve: {
extensions: ['.js', '.jsx', '.css']
},
module: {
rules: [
{
test: /\.jsx?/,
exclude: /node_modules/,
use: 'babel-loader'
}
]
}
};
module.exports = config;
The webpack.config.js file is my "corrected" one with the \ slashes. The original unedited version was:
const webpack = require('webpack');
const config = {
entry: __dirname + '/js/index.jsx',
output: {
path: __dirname + '/dist',
filename: 'bundle.js',
},
resolve: {
extensions: ['.js', '.jsx', '.css']
},
module: {
rules: [
{
test: /\.jsx?/,
exclude: /node_modules/,
use: 'babel-loader'
}
]
}
};
module.exports = config;

npm: How to set NODE_ENV in Windows (10)?

I am trying to add an npm script in package.json that sets NODE_ENV before doing something else (like running webpack). But although the syntax seems to be correct, NODE_ENV is not set when running under Windows 10.
Test script
"scripts": {
"test": "SET NODE_ENV=debug && echo %NODE_ENV%" }
The result from npm run test is "production" (provided NODE_ENV was set to "production" before running the script). Should be "debug".
What could be wrong? I even tried cross-env with no success.
Edit
To clarify my question: I cannot set any environment variable under Windows 10. And I need to call SET because I am running the script under Windows (10). Seems to be some rights problem (scripts not allowed to set environment variables?).
Another (or the actual) question would be: How can I create one script to build (using webpack) with creating minified versions of JavaScript files (for production), and one script to create non-minified versions (for development). So far I use following approach (see comments for the important parts):
Edit 2
I did not now that this probably made a difference, but in case it does: I worked with an React app created with create-react-app. I found the answer to my question, see below.
package.json:
{
"name": "test",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
// Scipts for build for development and for production
"build-dev": "SET NODE_ENV=debug webpack",
"build-release": "SET NODE_ENV=production webpack"
},
"author": "",
"license": "ISC",
"dependencies": {
"babel-core": "^6.24.1",
"babel-loader": "^7.0.0",
"babel-preset-env": "^1.4.0",
"babel-preset-react": "^6.24.1",
"debug": "^2.6.4",
"webpack": "^2.4.1"
}
}
webpack.config.js:
const path = require('path');
var webpack = require('webpack');
// Check if in debug environment
var debug = process.env.NODE_ENV !== "production";
module.exports = {
context: path.join(__dirname, 'src'),
entry: ['./index.js'],
output: {
path: path.join(__dirname, 'www/js'),
filename: 'index.js',
},
devtool: 'source-map',
module: {
rules: [
{
test: /\.jsx?$/,
exclude: /node_modules/,
use: ['babel-loader'],
}],
},
// Add the UglifyJs plugin only in debug mode
plugins: debug ? [] : [new webpack.optimize.UglifyJsPlugin({ mangle: false, sourcemap: false })],
resolve: {
modules: [
path.join(__dirname, 'node_modules')
]
}
};
This fails because setting NODE_ENV does not work for some reason. Using the command prompt directly like in the scripts:
SET NODE_ENV = debug
webpack
works by the way. That's proof that the configuration is okay, but just the npm script cannot set NODE_ENV.
Just in case you are STILL having issues setting the NODE_ENV in Windows 10 - this will help you. In your package.json file add the following:
"test": "SET \"NODE_ENV=test\""
If you plan on pushing this to Heroku - you will have to "export" the variable and your string would look like this (you are escaping the Windows-NEEDED quotes with a slash):
"test": "export NODE_ENV=test || SET \"NODE_ENV=test\""
Lastly, if you need a following command like mocha then the line would look like this:
"test": "export NODE_ENV=test || SET \"NODE_ENV=test\" && mocha server/**/*.name_of_files_plus_test.js"
Hope this helps someone :) - Mike
I found the answer to my question in the meantime, basically in the create-react-app readme: Firstly in an app created with create-react-app NODE_ENV cannot be manually overridden. Secondly, when setting environment variables, their name must start with "REACT_APP_". This was the solution for me.
In package.json:
"scripts": {
...
"build:staging": "SET REACT_APP_ENVIRONMENT=Staging && npm run build"
}
In the code:
if (process.env.REACT_APP_ENVIRONMENT === "Staging") ...
Did you try?
set DEBUG=* & npm run test
Make sure debug already installed
npm install debug --save
UPDATE:
To set environment variable in windows use
set NODE_ENV=dev //for development environment
In your case
"scripts": {
"test": "NODE_ENV=dev && echo %NODE_ENV%" }

GULP: gulp is not defined

As shown in the screen shot below I am not able to run gulp to concat the JavaScript files. Its saying that gulp is not defined.
I have tried the following commands:
npm install -g gulp
npm install gulp
npm install gulp --save-dev
I have also set the environment variables as following:
C:\Users\<user>\AppData\Roaming\npm;C:\Python27;C:\Users\<user>\AppData\Roaming\npm\node_modules;C:\Users\<user>\AppData\Roaming\npm\node_modules\gulp;
var concat = require('gulp-concat');
var rename = require('gulp-rename');
var uglify = require('gulp-uglify');
//script paths
var jsFiles = 'scripts/*.js',
jsDest = 'dist/scripts';
gulp.task('scripts', function() {
return gulp.src(jsFiles)
.pipe(concat('scripts.js'))
.pipe(gulp.dest(jsDest));
});
you just need to install and require gulp locally, you probably only installed it globally
At the command line
cd <project-root> && npm install --save-dev gulp
In your gulpfile.js
var gulp = require('gulp');
this is a different dependency than the command line dependency (that you installed globally). More specifically, it is the same NPM package, but the command line program will execute code usually from a different entry point in the NPM package then what require('X') will return.
If we go to the package.json file in the Gulp project on Github, it will tell the whole story:
{
"name": "gulp",
"description": "The streaming build system",
"version": "3.9.1",
"homepage": "http://gulpjs.com",
"repository": "gulpjs/gulp",
"author": "Fractal <contact#wearefractal.com> (http://wearefractal.com/)",
"tags": [ ],
"files": [
// ...
],
"bin": {
"gulp": "./bin/gulp.js"
},
"man": "gulp.1",
"dependencies": {
// ...
},
"devDependencies": {
// ...
},
"scripts": {
"prepublish": "marked-man --name gulp docs/CLI.md > gulp.1",
"lint": "eslint . && jscs *.js bin/ lib/ test/",
"pretest": "npm run lint",
},
"engines": {
"node": ">= 0.9"
},
"license": "MIT"
}
so at the command line:
$ gulp default
will execute this:
"bin": {
"gulp": "./bin/gulp.js"
},
on the other hand, require('gulp') in your code will return the value of this:
https://github.com/gulpjs/gulp/blob/master/index.js
normally we see this in a package.json file as:
"main": "index.js"
but since this is the default, they just omitted it (which is dumb IMO, better to be explicit, but they aren't the first project I have seen take the lame shorthand route.).
Its occurs on Windows and usually one of the following fixes it:
If you didn't, run npm install gulp on the project folder, even if
you have gulp installed globally.
Normally, It isn't a problem on Windows, but it could be a issue with
the PATH. The package will try to get the PATH from the environment,
but you can override it by adding exec_args to your gulp settings.
For example, on Ubuntu:
"exec_args": {
"path": "/bin:/usr/bin:/usr/local/bin"
}
Hope It will be OK.
Source: https://github.com/NicoSantangelo/sublime-gulp/issues/12