Whenever I perform a git pull from my master branch onto my server, all my React files seem to just disappear and the screen turns white.
The temporary workarounds I had found were:
Delete browser cookies, cache & site history, and then close the browser and try again.
Delete node_modules, npm install all react dependencies again
After a while, the site reappears and everything works as normal until the next time after a few pull requests, the problem appears again.
Any console I use on any browser shows no error messages at all.
After 2+ weeks of googling around, I can't seem to find anything that relates to this issue.
Here are my specs:
Ubuntu 16.04 server
Framework: React 16.2.0
webpack 1.12
nginx version: nginx/1.10.3 (Ubuntu)
git version 2.7.4
My webpack settings (for clarity, I compile all my react files with the command):
node_modules/.bin/webpack --config webpack.local.config.js
(local)
var path = require("path")
var webpack = require('webpack')
var BundleTracker = require('webpack-bundle-tracker')
var config = require('./webpack.base.config.js')
config.devtool = "#eval-source-map"
config.plugins = config.plugins.concat([
new BundleTracker({
filename: './webpack-stats-local.json'
}),
])
config.module.loaders.push({
test: /\.js[x]?$/,
exclude: /node_modules/,
loaders: ['react-hot-loader/webpack', 'babel'],
})
module.exports = config
(base)
var path = require("path")
var webpack = require('webpack')
module.exports = {
context: __dirname,
entry: {
App1: './path/to/App1/',
App2: './path/to/App2/',
// ...
App10: './path/to/App10/',
vendors: ['react'],
},
output: {
path: path.resolve('./backend/static/bundles/local/'),
filename: "[name]-[hash].js"
},
externals: {
"gettext":"gettext",
"django":"django",
}, // add all vendor libs
plugins: [
new webpack.optimize.CommonsChunkPlugin('vendors', 'vendors.js'),
],
module: {
loaders: []
},
resolve: {
modulesDirectories: ['node_modules', 'bower_components'],
extensions: ['', '.js', '.jsx']
},
}
Any help will be greatly appreciated
I solved this problem by updating Webpack to version 4 + updating the dependencies i used while getting rid of the ones i don't use.
Related
I'm having a bit of trouble adding react to a legacy application. While I found plenty of materials on getting started, I ran into a bunch of issues related to my particular configuration and exacerbated by my utter lack of webpack knowledge (so much time relying on react cli tools makes one lax).
My configuration:
./docs/jslib = my node_modules, that's where yarn installs modules
./docs/jscripts = my general js folder, various js scripts go there
./docs/jscripts/mini = my dist folder, some things get built/packed by gulp and end up here. This is where the built things are expected to go
./docs/jscripts/react(/react.js) = my desired root for react things, where the react.js is the entrypoint for DOM selection and rendering (at least for the first attempt).
My webpack config:
const path = require("path");
module.exports = {
entry: "./docs/jscript/react/react.js",
output: {
path: path.resolve(__dirname, "./docs/jscript/mini"),
filename: "react.js"
},
resolve: {
extensions: [".js", ".jsx"],
modules: [
path.resolve(__dirname, "./docs/jslib")
],
alias: {
'babel-loader': path.resolve(__dirname, "./docs/jslib/babel-loader")
}
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
include: [
path.resolve(__dirname, "./docs/jscript/react")
],
exclude: [
path.resolve(__dirname, "./docs/jslib")
],
use: {
loader: "babel-loader"
}
}
]
}
};
The error I get on running webpack:
yarn run v1.21.1
$ ./docs/jslib/babel-loader/node_modules/.bin/webpack --mode production
Insufficient number of arguments or no entry found.
Alternatively, run 'webpack(-cli) --help' for usage info.
Hash: 210250af48f3cf84fa4a
Version: webpack 4.41.6
Time: 75ms
Built at: 02/14/2020 9:23:09 AM
ERROR in Entry module not found: Error: Can't resolve 'babel-loader' in '/var/www/html'
I have webpack-cli, I can run webpack straight, I can run it from the modules bin folder, it's all the same problem - it can't find babel-loader even though babel-loader brings its own webpack script which I use, so the loader is obviously there in the "node_modules" that's actually on a different path.
From what I gathered, all I had to do was to add my custom node_modules path to the webpack config under the resolve settings, which has solved my initial errors related to packages not found (yet webpack still can't find the loader).
Note: if I symlink my ./docs/jslib as ./node_modules, it works as expected.
Is there something I'm missing?
Thanks!
After some digging, I found a solution and some details that other might want to keep in mind when configuring webpack in a rather non-standard context:
resolve: points to modules that are directly required in various scripts
resolveLoader: should point to the same, for the purpose of accessing loaders (which is what I needed)
Solution:
resolveLoader: {
extensions: ['.js', '.json', '.jsx'],
modules: [
path.resolve(__dirname, "./docs/jslib")
],
mainFields: ['loader', 'main']
}
I have an existing application that I am using "webpack-serve" as it was recommended to me by the developer(at that time he was not going to update webpack-dev-server anymore).
Anyways now it is deprecated and not being used, I got to back to webpack-dev-server but I am thinking if I should just go through the effort and try to use something like "Create React App" as I don't really know if I can use these old wepack.js files I made for webpack-serve and they also don't seem to work 100% as everytime I try to build a production build it gives me a dev build.
webpack.common.js
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CleanWebpackPlugin = require("clean-webpack-plugin");
const webpack = require('webpack');
module.exports = {
entry: ["#babel/polyfill", "./src/index.js"],
output: {
// filename and path are required
filename: "main.js",
path: path.resolve(__dirname, "dist"),
publicPath: '/'
},
module: {
rules: [
{
// JSX and JS are all .js
test: /\.js$/,
exclude: /node_modules/,
use: {
loader: "babel-loader",
}
},
{
test: /\.(eot|svg|ttf|woff|woff2)$/,
use: [
{
loader: 'file-loader',
options: {}
}
]
},
{
test: /\.(png|jpg|gif)$/,
use: [
{
loader: 'file-loader',
options: {}
}
]
}
]
},
plugins: [
new CleanWebpackPlugin(["dist"]),
new HtmlWebpackPlugin({
template: "./src/index.html"
}),
new webpack.IgnorePlugin(/^\.\/locale$/, /moment$/),
new webpack.DefinePlugin({
'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
})
]
};
webpack.dev
const path = require("path");
const merge = require("webpack-merge");
const convert = require("koa-connect");
const proxy = require("http-proxy-middleware");
const historyApiFallback = require("koa2-connect-history-api-fallback");
const common = require("./webpack.common.js");
module.exports = merge(common, {
// Provides process.env.NODE_ENV with value development.
// Enables NamedChunksPlugin and NamedModulesPlugin.
mode: "development",
devtool: "inline-source-map",
// configure `webpack-serve` options here
serve: {
// The path, or array of paths, from which static content will be served.
// Default: process.cwd()
// see https://github.com/webpack-contrib/webpack-serve#options
content: path.resolve(__dirname, "dist"),
add: (app, middleware, options) => {
// SPA are usually served through index.html so when the user refresh from another
// location say /about, the server will fail to GET anything from /about. We use
// HTML5 History API to change the requested location to the index we specified
app.use(historyApiFallback());
app.use(
convert(
// Although we are using HTML History API to redirect any sub-directory requests to index.html,
// the server is still requesting resources like JavaScript in relative paths,
// for example http://localhost:8080/users/main.js, therefore we need proxy to
// redirect all non-html sub-directory requests back to base path too
proxy(
// if pathname matches RegEx and is GET
(pathname, req) => pathname.match("/.*/") && req.method === "GET",
{
// options.target, required
target: "http://localhost:8080",
pathRewrite: {
"^/.*/": "/" // rewrite back to base path
}
}
)
)
);
}
},
module: {
rules: [
{
test: /\.(sa|sc|c)ss$/,
use: ["style-loader", "css-loader", "sass-loader"]
}
]
}
});
webpack.prod
const merge = require("webpack-merge");
const MiniCssExtractPlugin = require("mini-css-extract-plugin");
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin");
var BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const common = require("./webpack.common.js");
module.exports = merge(common, {
// Provides process.env.NODE_ENV with value production.
// Enables FlagDependencyUsagePlugin, FlagIncludedChunksPlugin,
// ModuleConcatenationPlugin, NoEmitOnErrorsPlugin, OccurrenceOrderPlugin,
// SideEffectsFlagPlugin and UglifyJsPlugin.
mode: "production",
devtool: "source-map",
// see https://webpack.js.org/configuration/optimization/
optimization: {
// minimize default is true
minimizer: [
// Optimize/minimize CSS assets.
// Solves extract-text-webpack-plugin CSS duplication problem
// By default it uses cssnano but a custom CSS processor can be specified
new OptimizeCSSAssetsPlugin({})
]
},
module: {
rules: [
{
test: /\.(sa|sc|c)ss$/,
// only use MiniCssExtractPlugin in production and without style-loader
use: [MiniCssExtractPlugin.loader, "css-loader", "sass-loader"]
}
]
},
plugins: [
// Mini CSS Extract plugin extracts CSS into separate files.
// It creates a CSS file per JS file which contains CSS.
// It supports On-Demand-Loading of CSS and SourceMaps.
// It requires webpack 4 to work.
new MiniCssExtractPlugin({
filename: "[name].css",
chunkFilename: "[id].css"
}),
new BundleAnalyzerPlugin()
]
});
Edit
If I where to go over to Create React App how would I handle this stuff?
I have a .babelrc with
"presets": ["#babel/env", "#babel/react"],
"plugins": [
["#babel/plugin-proposal-decorators", { "legacy": true }],
"#babel/plugin-transform-object-assign",
"#babel/plugin-proposal-object-rest-spread",
"transform-class-properties",
"emotion"
]
I think react-app takes care of some of the stuff but not sure if all. I also have if you noticed in webpack.common I am pollying filling everything, would I just need "react-app-polyfill."?
How can I add another "dev mode"
"scripts": {
"dev": "cross-env NODE_ENV=dev webpack-serve --config webpack.dev.js --open",
"prod": "cross-env NODE_ENV=prod webpack -p --config webpack.prod.js",
"qa": "cross-env NODE_ENV=QA webpack --config webpack.prod.js"
},
I need to setup the Node_ENV for QA as I have a check to point to my api that changes in each enviroment.
it's a simple as below today:
npx create-react-app .
I've had to do something like this a couple times. This has been my approach:
create-react-app my-app-cra // clean slate
npm i [list of dependencies] // minus any build, compile, transpile, etc. dependencies
Copy over my src folder, preserving as much of the structure as possible
npm start // and keep fingers crossed! Typically, a bit of manual work is involved
To preserve your git history:
Copy your src to a folder outside your repo
Clean your repo git rm -rf
Perform the above steps (create react app, install deps, copy src back in)
git add // If you preserve your folder structure, git will find the copied over files (and will notice a possible change in path) and handles gracefully, preserving history.
Both create-react-app and webpack 4 are good options and very simple. In my opinion, create-react-app is the most practical.
In order to conserve your git history, I recommend:
create a branch and go to it.
install and save the dependencies and dev-dependencies of create-react-app. you will see them in your package.json file.
do the configuration. use the create-react-app repo as an example.
if it works fine, return to your master branch and merge this branch with the migration.
Execute npm i in order to install the dependencies you added from your branch.
I am trying to implement server side rendering on my react app, but having trouble with this one error.
this is my webpack.config.js file. When I run the script npm start everything compiles correctly.
var fs = require('fs');
var nodeModules = {};
fs.readdirSync('node_modules')
.filter(function(x) {
return ['.bin'].indexOf(x) === -1;
})
.forEach(function(mod) {
nodeModules[mod] = 'commonjs ' + mod;
});
module.exports = {
entry: [
'./server.js'
],
target: 'node',
output: {
path: __dirname,
publicPath: '/',
filename: 'bundle.js'
},
externals: nodeModules,
module: {
loaders: [{
exclude: /node_modules/,
loader: 'babel',
query: {
presets: ['react', 'es2015', 'stage-1']
}
}]
},
resolve: {
extensions: ['', '.js', '.jsx']
},
devServer: {
historyApiFallback: true,
contentBase: './'
}
};
I believe the main issue is that webpack thinks bundle.js is build for node environment. Therefore it assumes that require is available. However it is meant for the browser, it will throw an error since require is not available. I'm not really sure if your webpack.config.js is for the server or the browser, since the entry point is the server.js and yet the output is for bundle.js, which I assume meant for the browser.
Have a look on server rendering tutorial here. Basically, you have to have a webpack config file for server and the browser. The server webpack config file would have an entry point where your server is defined. Whereas the browser webpack config file would have an entry point where react-dom render method is called. Then, make sure that the output of the browser webpack config is the one that is used in the html and not the server one.
I have finished my ReactJS app and I want to put it in production. I run next command: webpack --progress -p but in chrome F12 I get next error: index.js:1 Warning: It looks like you're using a minified copy of the development build of React. When deploying React apps to production, make sure to use the production build which skips development warnings and is faster. See WebSiteFbReactJs for more details..
It is my webpack.config.js:
'use strict';
const WEBPACK = require('webpack');
const PATH = require('path');
const CopyFiles = require('copy-webpack-plugin');
const BaseName = "/upct";
module.exports = {
resolve: {
extensions: ['', '.js', '.jsx']
},
context: __dirname,
entry: {
app: ['./src/index.jsx']
},
output: {
path: PATH.join(__dirname, '/public'),
/*path: './public',*/
publicPath: BaseName+'/',
filename: 'index.js'
},
devServer: {
host: 'localhost',
port: 3000,
contentBase: PATH.join(__dirname, '/public'),
inline: true,
historyApiFallback: true,
headers: { "Access-Control-Allow-Origin": "*" }
},
module: {
loaders: [
{
test: /(\.js|.jsx)$/,
loader: 'babel',
query: {
"presets": [
"es2015",
"react",
"stage-0"
],
"plugins": [
"react-html-attrs",
"transform-decorators-legacy",
"transform-class-properties"
]
}
}
]
},
plugins: [
new WEBPACK.DefinePlugin({
BASENAME: JSON.stringify(BaseName)
})
]
}
What could this error be?. It is all OK, right? How could I solve this? Thank you.
EDIT: I am getting next error too: DevTools failed to parse SourceMap: http://MYSERVER.com/upct/src/css/bootstrap.css.map
Please add NODE_ENV = 'production' environmental variable to your Webpack build in order to disable debug information and warnings, most of the property type checks and other developer-friendly tools. It will make the app faster but harder to debug. Use this only when deploying to the production.
In your case, in the plugins section just add:
new WEBPACK.DefinePlugin({
'process.env': {
'NODE_ENV': JSON.stringify('production')
}
}),
Please see documentation about optimizing the production build with React, especially Webpack section.
As for the error with the source maps, it seems that the link is broken and returns 404 Not Found error so Chrome can't fetch the original source code mapping for Bootstrap's CSS. That's not a big issue as you probably won't be looking at it's source but that might be a signal that your Webpack build doesn't deploy source maps when building the app. Please add devtool: 'source-map' to your config file in order to produce source maps which will improve the debugging experience on production by translating bundled code to original source files.
UglifyJs will minimize the code size by renaming variables, function names and by other optimization tricks. You can add it to your plugins section of the config file the same way:
new WEBPACK.optimize.UglifyJsPlugin({
compress: {
// suppresses warnings, usually from module minification
warnings: false,
},
}),
There are many possible optimizations, for more information please see this optimization guide.
I'm currently experimenting with a monorepo architecture.
What I would like to do is in my web package where I run webpack dev server I'd like it to watch certain node_modules (symlinked local packages) for changes and trigger a "rebuild".
This way I'd be able to build dependencies separately and my browser would react to those changes.
My webpack config is the following:
var loaders = require('./../../../build/loaders-default');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var path = require('path');
var webpack = require('webpack');
module.exports = {
entry: ['./src/index.ts'],
output: {
filename: 'build.js',
path: path.join(__dirname, 'dist')
},
resolve: {
extensions: ['.ts', '.js', '.json']
},
resolveLoader: {
modules: ['node_modules']
},
devtool: 'inline-source-map',
devServer: {
proxy: [
{
context: ['/api-v1/**', '/api-v2/**'],
target: 'https://other-server.example.com',
secure: false
}
]
},
plugins: [
new HtmlWebpackPlugin({
template: './src/index.html',
inject: 'body',
hash: true
}),
new webpack.ProvidePlugin({
$: 'jquery',
jQuery: 'jquery',
'window.jQuery': 'jquery',
'window.jquery': 'jquery'
})
],
module:{
loaders: loaders
}
};
Loaders are just the usual stuff included.
You can config in in webpack.config file or in WebpackDevServer option, to watch for changes also in node_modules (i think that by default webpack watching for changes in all files)
https://webpack.js.org/configuration/watch/#watchoptions-ignored
in the following example webpack ignored all changes in node_modules folder except specific module.
watchOptions: {
ignored: [
/node_modules([\\]+|\/)+(?!some_npm_module_name)/,
/\some_npm_module_name([\\]+|\/)node_modules/
]
}
ignored[0] = Regex to ignore all node_modules that not started with some_npm_module_name
ignored[1] = Regex to ignore all node_modules inside some_npm_module_name
You may also used this link npm linked modules don’t find their dependencies
UPDATE: I'm currently using Next.js 11, and it seems this is no longer necessary.
Granted this question is not regarding Next.js or any specific framework, I'd like to post an answer related to Next.js here since I arrived here from Google as others might also.
Here is what worked for me in my next.config.js:
module.exports = {
// ...
webpackDevMiddleware: config => {
// Don't ignore all node modules.
config.watchOptions.ignored = config.watchOptions.ignored.filter(
ignore => !ignore.toString().includes('node_modules')
);
// Ignore all node modules except those here.
config.watchOptions.ignored = [
...config.watchOptions.ignored,
/node_modules\/(?!#orgname\/.+)/,
/\#orgname\/.+\/node_modules/
];
return config;
},
// ...
}
This targets a specific organization of packages. If you need to just target a specific package:
module.exports = {
// ...
webpackDevMiddleware: config => {
// Don't ignore all node modules.
config.watchOptions.ignored = config.watchOptions.ignored.filter(
ignore => !ignore.toString().includes('node_modules')
);
// Ignore all node modules except those here.
config.watchOptions.ignored = [
...config.watchOptions.ignored,
/node_modules([\\]+|\/)+(?!my-node-module)/,
/\my-node-module([\\]+|\/)node_modules/
];
return config;
},
// ...
}
This builds on Elhay's answer.
snapshot.managedPaths
A common use case for managedPaths would be to exclude some folders from node_modules, e.g. you want webpack to know that files in the node_modules/#azure/msal-browser folder are expected to change, which can be done with a regular expression like the one below:
module.exports = {
snapshot: {
managedPaths: [
/^(.+?[\\/]node_modules[\\/](?!(#azure[\\/]msal-browser))(#.+?[\\/])?.+?)[\\/]/,
],
},
};