karma-webpack not loading AngularJS bundle - angularjs

I recently started the move from a custom gulp script that used to take care of all sorts of stuff to webpack. I have it working to a point where transpiling, bundling and serving the client app in the browser works great.
Now, when I was using gulp to run my karma tests against the bundled app.js file, the gulp script would first bundle the app.js file and then spit it into the dist folder. This file would then be used by karma to run the tests against it. My gulp test task would also watch for any test file changes or for the bundle file change, and re-run the tests based on that.
With webpack, I understand this dist/app.js resides in-memory, rather than being written to the disk (at least that's how I set it up). The problem with that is that it seems that my bundled app (which gets served fine with webpack-dev-server --open) does not get loaded by karma for some reason and I can't figure out what the missing piece of the puzzle is.
This is how my folder structure looks like (I left just the most basic stuff that could be relevant to the issue):
package.json
webpack.config.js
karma.conf.js
src/
--app/
----[other files/subfolders]
----app.ts
----index.ts
--boot.ts
--index.html
tests/
--common/
----services/
------account.service.spec.js
This is my webpack.config.js
var path = require("path");
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CleanWebpackPlugin = require("clean-webpack-plugin");
const ForkTsCheckerWebpackPlugin = require("fork-ts-checker-webpack-plugin");
module.exports = {
context: path.join(__dirname),
entry: "./src/boot.ts",
plugins: [
new webpack.HotModuleReplacementPlugin(),
new ForkTsCheckerWebpackPlugin(),
new CleanWebpackPlugin(["dist"]),
new HtmlWebpackPlugin({
template: "./src/index.html"
})
],
module: {
rules: [
{
test: /\.scss$/,
use: [{
loader: "style-loader"
}, {
loader: "css-loader"
}, {
loader: "sass-loader"
}]
},
{
test: /\.tsx?$/,
use: [{
loader: "ts-loader",
options: {
transpileOnly: true,
exclude: /node_modules/
}
}]
},
{
test: /\.html$/,
loaders: "html-loader",
options: {
attrs: [":data-src"],
minimize: true
}
}
]
},
resolve: {
extensions: [".tsx", ".ts", ".js"],
alias: {
"common": path.resolve(__dirname, "src/app/common"),
"common/*": path.resolve(__dirname, "src/app/common/*"),
"modules": path.resolve(__dirname, "src/app/modules"),
"modules/*": path.resolve(__dirname, "src/app/modules/*"),
}
},
output: {
filename: "app.js",
path: path.resolve(__dirname, "dist")
},
devtool: "inline-source-map",
devServer: {
historyApiFallback: true,
hot: false,
contentBase: path.resolve(__dirname, "dist")
}
};
This is my karma.conf.js
const webpackConfig = require("./webpack.config");
module.exports = function (config) {
config.set({
frameworks: ["jasmine"],
files: [
"node_modules/angular/angular.js",
"node_modules/angular-mocks/angular-mocks.js",
"dist/app.js", // not sure about this
"tests/common/*.spec.js",
"tests/common/**/*.spec.js"
],
preprocessors: {
"dist/app.js": ["webpack", "sourcemap"], // not sure about this either
"tests/common/*.spec.js": ["webpack", "sourcemap"],
"tests/common/**/*.spec.js": ["webpack", "sourcemap"]
},
webpack: webpackConfig,
webpackMiddleware: {
noInfo: true,
stats: {
chunks: false
}
},
reporters: ["progress", "coverage"], // , "teamcity"],
coverageReporter: {
dir: "coverage",
reporters: [
{ type: "html", subdir: "html" },
{ type: "text-summary" }
]
},
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: [
"PhantomJS"
//"Chrome"
],
singleRun: false,
concurrency: Infinity,
browserNoActivityTimeout: 100000
});
};
This is the boot.ts which is basically the entry point to the app:
import * as app from "./app/app";
import "./styles/app.scss";
// This never gets written to the console
// so I know it never gets loaded by karma
console.log("I NEVER OUTPUT TO CONSOLE");
This is the app.ts (which then references anything below it:
import * as ng from "angular";
import * as _ from "lodash";
import "#uirouter/angularjs";
import "angular-cookies";
import "angular-material"
import "angular-local-storage";
import "angular-sanitize";
import "angular-messages";
import "angular-file-saver";
import "angular-loading-bar";
import "satellizer";
export * from "./index";
import * as Module from "common/module";
import * as AuthModule from "modules/auth/module";
import * as UserModule from "modules/user/module";
import { MyAppConfig } from "./app.config";
import { MyAppRun } from "./app.run";
export default ng.module("MyApp", [
"ngCookies",
"ngSanitize",
"ngMessages",
"ngFileSaver",
"LocalStorageModule",
"ui.router",
"ngMaterial",
"satellizer",
"angular-loading-bar",
Module.name,
AuthModule.name,
UserModule.name
])
.config(MyAppConfig)
.run(MyAppRun);
And finally, this is the account.service.spec.js
describe("Account service", function () {
// SETUP
var _AccountService;
beforeEach(angular.mock.module("MyApp.Common"));
beforeEach(angular.mock.inject(function (_AccountService_) {
// CODE NEVER GETS IN HERE EITHER
console.log("I NEVER OUTPUT TO CONSOLE");
_AccountService = _AccountService_;
}));
function expectValidPassword(result) {
expect(result).toEqual({
minCharacters: true,
lowercase: true,
uppercase: true,
digits: true,
isValid: true
});
}
// TESTS
describe(".validatePassword()", function () {
describe("on valid password", function () {
it("returns valid true state", function () {
expectValidPassword(_AccountService.validatePassword("asdfASDF123"));
expectValidPassword(_AccountService.validatePassword("as#dfAS!DF123%"));
expectValidPassword(_AccountService.validatePassword("aA1234%$2"));
expectValidPassword(_AccountService.validatePassword("YYyy22!#"));
expectValidPassword(_AccountService.validatePassword("Ma#38Hr$"));
expectValidPassword(_AccountService.validatePassword("aA1\"#$%(#/$\"#$/(=/#$=!\")(\")("));
})
});
});
});
And this is the output of running the karma start
> npm test
> myapp#1.0.0 test E:\projects\Whatever
> karma start
clean-webpack-plugin: E:\projects\Whatever\dist has been removed.
Starting type checking service...
Using 1 worker with 2048MB memory limit
31 10 2017 21:47:23.372:WARN [watcher]: Pattern "E:/projects/Whatever/dist/app.js" does not match any file.
31 10 2017 21:47:23.376:WARN [watcher]: Pattern "E:/projects/Whatever/tests/common/*.spec.js" does not match any file.
ts-loader: Using typescript#2.4.2 and E:\projects\Whatever\tsconfig.json
No type errors found
Version: typescript 2.4.2
Time: 2468ms
31 10 2017 21:47:31.991:WARN [karma]: No captured browser, open http://localhost:9876/
31 10 2017 21:47:32.004:INFO [karma]: Karma v1.7.1 server started at http://0.0.0.0:9876/
31 10 2017 21:47:32.004:INFO [launcher]: Launching browser PhantomJS with unlimited concurrency
31 10 2017 21:47:32.010:INFO [launcher]: Starting browser PhantomJS
31 10 2017 21:47:35.142:INFO [PhantomJS 2.1.1 (Windows 8 0.0.0)]: Connected on socket PT-pno0eF3hlcdNEAAAA with id 71358105
PhantomJS 2.1.1 (Windows 8 0.0.0) Account service .validatePassword() on valid password returns valid true state FAILED
forEach#node_modules/angular/angular.js:410:24
loadModules#node_modules/angular/angular.js:4917:12
createInjector#node_modules/angular/angular.js:4839:30
WorkFn#node_modules/angular-mocks/angular-mocks.js:3172:60
loaded#http://localhost:9876/context.js:162:17
node_modules/angular/angular.js:4958:53
TypeError: undefined is not an object (evaluating '_AccountService.validatePassword') in tests/common/services/account.service.spec.js (line 742)
webpack:///tests/common/services/account.service.spec.js:27:0 <- tests/common/services/account.service.spec.js:742:44
loaded#http://localhost:9876/context.js:162:17
PhantomJS 2.1.1 (Windows 8 0.0.0) Account service .validatePassword() on valid amount of characters returns minCharacters true FAILED
forEach#node_modules/angular/angular.js:410:24
loadModules#node_modules/angular/angular.js:4917:12
createInjector#node_modules/angular/angular.js:4839:30
WorkFn#node_modules/angular-mocks/angular-mocks.js:3172:60
node_modules/angular/angular.js:4958:53
TypeError: undefined is not an object (evaluating '_AccountService.validatePassword') in tests/common/services/account.service.spec.js (line 753)
webpack:///tests/common/services/account.service.spec.js:38:0 <- tests/common/services/account.service.spec.js:753:37
PhantomJS 2.1.1 (Windows 8 0.0.0): Executed 2 of 2 (2 FAILED) ERROR (0.017 secs / 0.015 secs)
Please note the few places where I left console.logs which never get triggered. That's how I know the app doesn't get loaded. That and the fact that jasmine is not able to inject the service I want to test.
I'm using:
karma v1.7.1
karma-webpack v2.0.5
webpack v3.3.0
Any ideas? What am I doing wrong? I'm under the impression that my webpack.config.js is supposed to bundle my AngularJS/TS app and then essentially feed it to karma, but for whatever reason, that doesn't seem to work. Or do I have some fundamental misconception of how this is supposed to work?
Thank you.
I extracted a few files into a simple app and put it to github so the issue could be easily reproduced.
npm install # install deps
npm run serve:dev # run the app - works
npm run test # run karma tests - doesn't work
Edit:
I managed to make the tests run by replacing the:
"dist/app.js"
in karma setup with
"src/boot.ts"
but that wouldn't drill down or load/import the rest of the app. Then I tried importing only the class I want to test to the spec but then I couldn't mock any DI-injected services that the class I'm testing is using. Anyway, I pretty much gave up on this at this stage and stopped trying to figure out how to do this, moving to ang2+.

I faced a similar issue during transferring my AngularJS project building from Grunt to Webpack and tried 2 different approaches.
1. Webpack and Karma as two separate processes. I made an npm-script running webpack and karma in parallel. It looked like
"dev-build": "webpack --config webpack/development.js",
"dev-test": "karma start test/karma.development.conf.js",
"test": "concurrently --kill-others --raw \"npm run dev-build\" \"npm run dev-test\""
Instead of concurrently you may do anything else, npm-run-all or even &. In that configuration Karma did not have any Webpack stuff, she just watched the ./temp folder for built distributive and worked stand-alone, re-running herself each time the tests or distributive had been changed. Webpack was started in the dev-mode (via "dev-build" script), he watched the ./src folder and compiled distributive into the ./temp folder. When he updated ./temp, Karma started tests re-running.
It worked, despite the problems of first Karma fail. Karma started tests before the Webpack first compilation had been finished. It's not critical. Also, a playing with restartOnFileChange setting could help... Maybe there is another good workaround. I didn't finished this story, I switched to option 2, which I believe fits the Webpack-way a bit more than just described one.
2. Karma is the only process, which uses Webpack. I refused the ./temp folder and decided that for the dev-mode all operations should be in-memory. Dev-mode Webpack got following settings (./webpack/development.js):
entry: { 'ui-scroll': path.resolve(__dirname, '../src/ui-scroll.js') },
output: { filename: '[name].js' }, // + path to ./dist in prod
devtool: 'inline-source-map', // 'source-map' in prod
compressing: false,
watch: true
Dev-mode Karma (./test/karma.development.conf.js):
files: [
// external libs
// tests specs
'../src/ui-scroll.js' // ../dist in prod
],
preprocessors: { // no preprocessors in prod
'../src/ui-scroll.js': ['webpack', 'sourcemap']
},
webpack: require('../webpack/development.js'), // no webpack in prod
autoWatch: true,
keepalive: true,
singleRun: false
This also required two npm packages to be installed: karma-webpack and karma-sourcemap-loader. The first option looks more familiar after Grunt/gulp, but this one is simpler, shorter and more stable.

Related

Make webpack-dev-server to do hot reloading AND eliminate EMPTY response error in React

I have been trying to make React app development easier by using reloading of the app when I modify the files and I tried webpack-dev-server for that (Please, see my previous thread: Can't set up webpack-dev-server to start React app). I made hot reloading working but got an issue: timeouts started to occur on my requests and I see the empty response errors in console. There are threads that discuss the issue, e.g.: https://github.com/webpack/webpack-dev-server/issues/183
but so far I could not make it working. Setting --host 0.0.0.0 is not working, setting --port 3000 eliminates empty response error but hot reloading is gone... Below is my webpack relevant config:
devServer: {
index: '',
open: true,
proxy: {
context: () => true, // endpoints which you want to proxy
target: 'http://localhost:3000' // your main server address
}
},
entry: {
app: ['babel-polyfill', './views/index.js']
//vendor: ["react","react-dom"]
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, './public')
},
devtool: "#eval-source-map",
...
I am starting the app by running npm run dev, here is a part of the package.json:
"scripts": {
"client": "webpack-dev-server --mode development --devtool inline-source-map --port 3000 --content-base public --hot",
"server": "node ./bin/www",
"dev": "concurrently \"npm run server\" \"npm run client\"",
},
So, above if we remove --port 3000 hot reloading on the front end part starts working, but then the timeout is happening. Also, upon modification of the server side code the app is not reloaded unfortunately and I am not sure how to add this feature too. I am using react-hot-loader:
import React from 'react';
import ControlledTabs from './ControlledTabs'
import { hot } from 'react-hot-loader/root'
class App extends React.Component {
render() {
return (
<ControlledTabs/>
);
}
}
module.exports = hot(App);
I think it should be related to the devServer configs most probably and how the webpack-dev-server is started. I just want to find a WORKING way of doing hot reloading instead of falling back into build - run cycle that is annoying and inefficient.
Also, it is really hard to say, what is going wrong, whether --port 3000 is really the issue. I noticed that the webpack-dev-server is somehow working in a very unpredictable way on my project meaning that after doing changes and launching the app I see one result, but then I restart webpack-dev-server and see a different result as if webpack-dev-server is doing something behind the scenes what it wants to and whenever it wants to without notifying me about that.
Update
I changed webpack.config.js to:
watch: true,
devServer: {
index: '',
open: true,
proxy: {
context: () => true, // endpoints which you want to proxy
target: 'http://localhost:3000' // your main server address
}
},
entry: {
app: ['babel-polyfill', './views/index.js']
//vendor: ["react","react-dom"]
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, './public')
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
],
And removed react-hot-loader from the React entry point:
import React from 'react';
import ControlledTabs from './ControlledTabs'
class App extends React.Component {
render() {
return (
<ControlledTabs/>
);
}
}
module.exports = App;
Because otherwise it was giving me a syntax error in console, webpack could not start. After doing that if I modify any react file, whole webpage is reloaded it seems and the net::ERR_EMPTY_RESPONSE remains...
Add a watch to your webpack config.
watch: true
Also, you need to enable module replacement loading within the webpack dev server.
In short, if you see how this config is setup, this is a working example of hot reloading for a very basic react app. It uses ExpressJS as well.
https://github.com/chawk/bare_bones_react/blob/master/webpack.config.js
const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const webpack = require('webpack');
const express = require('express');
module.exports = {
entry: {
app: './src/index.js'
},
devServer: {
hot: true,
compress: true,
contentBase: path.join(__dirname, 'dist'),
open: 'Chrome',
before(app) {
app.use('/static', express.static(path.resolve(__dirname, 'dist')))
}
},
devtool: 'source-map',
output: {
filename: './js/[name].bundle.js',
path: path.resolve(__dirname, 'dist')
},
plugins: [
new webpack.HotModuleReplacementPlugin(),
new HtmlWebpackPlugin({
template: './server/index.html'
})
],
module: {
rules: [
{
test: /\.js$/,
exclude: /node_modules/,
use: ['babel-loader']
}
]
},
resolve: {
extensions: [
'.js'
]
}
}

How to run tests in Angular & AngularJs hybrid app?

As I want to migrate my AngularJs application to Angular 7, I created a hybrid app using ngUpgrade. The old AngularJs app is now embedded in the new Angular one.
When I run ng test it fires my Angular tests which is fine. But I also want to run the old tests written in AngularJs.
At the moment my Karma config looks like:
'use strict';
const webpackConfig = require('./karma.webpack.config');
module.exports = function (config) {
config.set({
basePath: '',
frameworks: ['jasmine', '#angular-devkit/build-angular', 'es6-shim'],
plugins: [
require('karma-jasmine'),
require('karma-chrome-launcher'),
require('karma-jasmine-html-reporter'),
require('karma-coverage-istanbul-reporter'),
require('#angular-devkit/build-angular/plugins/karma'),
require('karma-es6-shim'),
require('karma-junit-reporter'),
require('karma-webpack'),
],
client:{
clearContext: false // leave Jasmine Spec Runner output visible in browser
},
coverageIstanbulReporter: {
dir: require('path').join(__dirname, 'coverage'),
reports: [ 'html', 'lcovonly' ],
fixWebpackSourcePaths: true
},
mime: {
'text/x-typescript': ['ts','tsx']
},
exclude: [
'**/*.html'
],
preprocessors: {
'./karma.entrypoint.ts': ['webpack']
},
webpack: webpackConfig,
webpackMiddleware: {
noInfo: true,
stats: 'errors-only'
},
junitReporter : {
// results will be saved as $outputDir/$browserName.xml
outputDir : 'build/test-results/test/'
},
reporters: ['progress', 'kjhtml', 'junit'],
port: 9876,
colors: true,
logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
singleRun: false
});
};
The ./karma.webpack.config file is:
const config = require('./webpack.config.js')();
const webpack = require('webpack');
const path = require('path');
const nibStylusPlugin = require('nib');
const ForkTsCheckerWebpackPlugin = require('fork-ts-checker-webpack-plugin');
module.exports = Object.assign({}, config, {
context: path.resolve(__dirname, '.'),
entry: {
test: './karma.entrypoint.ts'
},
mode: 'development',
devtool: 'cheap-module-inline-source-map',
optimization: {
splitChunks: false,
runtimeChunk: false
},
plugins: [
new ForkTsCheckerWebpackPlugin(),
new webpack.ProvidePlugin({
"window.jQuery": "jquery",
tv4: "tv4"
}),
new webpack.LoaderOptionsPlugin({
options: {
stylus: {
use: [nibStylusPlugin()],
import: ['~nib/lib/nib/index.styl'],
}
}
})
]
});
And last but not least the karma.entrypoint.ts:
import 'jquery';
import 'angular';
import 'angular-mocks';
import * as moment from 'moment';
import{appConfigMock} from './karma.app-mock.config';
window['__APP_CONFIG__'] = appConfigMock;
(<any>moment).suppressDeprecationWarnings = true;
const testsContext = (<any>require).context('./src/app/', true, /\.spec\.ts$/);
testsContext.keys().forEach(testsContext);
Before, when I had only the AngularJs app, I run the tests with a very similar structure by using karma command. It utilized my webpack config to create a new karma webpack config. Now, when I run it through the ng test command, I even cannot require the './karma.webpack.config' at the beginning on karma configuration (I get Invalid config file! TypeError: require(...) is not a function).
How should I approach this case to run all the tests?
I finally solved it by running the tests separately but with one npm command, npm run test:
"test-ng1": "cross-env APP_CONFIG=testing NODE_ENV=development karma start --single-run",
"test-ng2-apps": "ng test --watch=false --ts-config=./karma.tsconfig.json",
"test": "yarn test-ng2-apps && yarn test-ng1",

Webpack+SemanticUI+React: process is not defined

I have found numerous posts about the Webpack error:
Uncaught ReferenceError: process is not defined
most of which suggest adding a plugin to the webpack.config.js:
plugins: [
// ...
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(process.env.NODE_ENV || 'development')
}
}),
// ...
]
however this does not seem to do the trick in my case.
To make things easy, I have created a repo with the bare minimum to setup SemanticUI-React with Webpack, which should be straightforward to navigate. My config in webpack.config.js is heavily inspired from this recent tutorial which seems to have a lot of positive comments.
To reproduce the error, just clone the repo on your machine (I use yarn, but this should work with npm too):
git clone https://github.com/sheljohn/minimal-semantic-react
cd minimal-semantic-react/
yarn install
yarn run serve
which opens at localhost:3000, and the error can be seen in the developer console.
As far as I understand, it seems that when React loads, it is looking to determine whether production or development mode is set, using the variable process.env.NODE_ENV, which is undefined in the browser.
This might be related to the target field in the Webpack config (set to web by default); but since React is loaded from CDN, prior to the bundle, I guess it doesn't know about what WebPack is doing, which makes me perplex as to why adding a plugin in the config would change anything...
Hence my question: is it possible to use semantic-ui-react by declaring the big libs (React, ReactDOM, semantic) as externals? Everything works fine if I bundle them, but the bundle ends up around 4MB, which is quite big.
Additional Details
Error as seen in Chrome (OSX High Sierra, v66.0.3359.181, dev console):
react.development.js:14 Uncaught ReferenceError: process is not defined
at react.development.js:14
(anonymous) # react.development.js:14
and code excerpt at line 14:
if (process.env.NODE_ENV !== "production") {
File webpack.config.js
const path = require("path");
const webpack = require("webpack");
const publicFolder = path.resolve(__dirname, "public");
module.exports = {
entry: "./src/index.jsx",
target: "web",
output: {
path: publicFolder,
filename: "bundle.js"
},
devServer: {
contentBase: publicFolder,
port: 3000
},
externals: {
'jquery': 'jQuery',
'lodash': '_',
'react': 'React',
'react-dom': 'ReactDOM',
'semantic-ui-react': 'semantic-ui-react'
},
module: {
rules: [
{
test: /\.(js|jsx)$/,
exclude: /(node_modules|bower_components)/,
use: {
loader: 'babel-loader'
}
}
]
},
plugins: [
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: JSON.stringify(process.env.NODE_ENV || 'development')
}
}),
new webpack.HotModuleReplacementPlugin()
]
};
File .babelrc
{
"presets": ["env", "react"]
}
I think I finally solved this:
Mistake #1: I was using cjs versions of the React libs from cdnjs, when I should have been using umd instead. Although UMD style is ugly, it seems to work fine within browsers, whereas CommonJS uses require for example. See this post for a comparison of AMD / CommonJS / UMD.
Mistake #2: in webpack.config.js, the "name" for the external semantic-ui-react should be semanticUIReact (case sensitive). This is what is defined in the window global when the script is loaded from the CDN (e.g. like jQuery or React).
I updated the repository with these fixes, and you should be able to reproduce that working example on your machine. This repository contains the bare minimum needed to get SemanticUI, React and Webpack working together. This would have saved me a lot of time, so hopefully other people get to benefit from that!
Everything works fine if I bundle them, but the bundle ends up around 4MB, which is quite big.
It's because you bundle them in "development" mode. Try using "production" in your script instead, it will be much smaller.
"build": "webpack --mode production"
If you bundle everything in production, without specifying external, it will be better for a standalone app.

Whitescreen of death after pulling from git repo (ReactJS, Nginx)

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.

Deploying ReactJS app Production

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.

Resources