How to debug a JSPM-SystemJS-AngularJS project in Webstorm 11 - angularjs

Debugging my project in Webstorm 11 I get an error.
If I run the project instead, it runs fine.
I am following the JSPM - Getting Started. Debugging the Javascript module is fine. The error occurs once I try to integrate Angular into my project.
What do I do wrong?
Error when debugging:
Uncaught (in promise) Error: ReferenceError: module is not defined
at eval (http://localhost:63342/JSPM-Angular-playground/jspm_packages/npm/babel-core#5.8.35.js:1:1)
Evaluating http://localhost:63342/JSPM-Angular-playground/jspm_packages/npm/babel-core#5.8.35.js
Error loading http://localhost:63342/JSPM-Angular-playground/jspm_packages/npm/babel-core#5.8.35.js
Error loading http://localhost:63342/JSPM-Angular-playground/app/app.js
t
g
(anonymous function)
Project setup:
package.json
{
"jspm": {
"dependencies": {
"angular": "github:angular/bower-angular#^1.5.0"
},
"devDependencies": {
"babel": "npm:babel-core#^5.8.24",
"babel-runtime": "npm:babel-runtime#^5.8.24",
"core-js": "npm:core-js#^1.1.4"
}
},
"devDependencies": {
"jspm": "^0.16.31"
}
}
config.js
System.config({
baseURL: "/JSPM-Angular-playground",
defaultJSExtensions: true,
transpiler: "babel",
babelOptions: {
"optional": [
"runtime",
"optimisation.modules.system"
]
},
paths: {
"github:*": "jspm_packages/github/*",
"npm:*": "jspm_packages/npm/*"
},
map: {
"angular": "github:angular/bower-angular#1.5.0",
"babel": "npm:babel-core#5.8.35",
"babel-runtime": "npm:babel-runtime#5.8.35",
"core-js": "npm:core-js#1.2.6",
"github:jspm/nodelibs-assert#0.1.0": {
"assert": "npm:assert#1.3.0"
},
"github:jspm/nodelibs-path#0.1.0": {
"path-browserify": "npm:path-browserify#0.0.0"
},
"github:jspm/nodelibs-process#0.1.2": {
"process": "npm:process#0.11.2"
},
"github:jspm/nodelibs-util#0.1.0": {
"util": "npm:util#0.10.3"
},
"npm:assert#1.3.0": {
"util": "npm:util#0.10.3"
},
"npm:babel-runtime#5.8.35": {
"process": "github:jspm/nodelibs-process#0.1.2"
},
"npm:core-js#1.2.6": {
"fs": "github:jspm/nodelibs-fs#0.1.2",
"path": "github:jspm/nodelibs-path#0.1.0",
"process": "github:jspm/nodelibs-process#0.1.2",
"systemjs-json": "github:systemjs/plugin-json#0.1.0"
},
"npm:inherits#2.0.1": {
"util": "github:jspm/nodelibs-util#0.1.0"
},
"npm:path-browserify#0.0.0": {
"process": "github:jspm/nodelibs-process#0.1.2"
},
"npm:process#0.11.2": {
"assert": "github:jspm/nodelibs-assert#0.1.0"
},
"npm:util#0.10.3": {
"inherits": "npm:inherits#2.0.1",
"process": "github:jspm/nodelibs-process#0.1.2"
}
}
});

Related

transpiled code (babel) seems not working in Browser

Hi I'm working on an existing app which needs enhancements. The app is built using angularJS, Babel, webpack. I struggled running the app locally and finally succeeded in running it after making changes to how we call a basedirective (like below) which was using babel next generation javascript notation to regular notation (a compiler is present on babel site to do this).
function filtersDirective() {
return {
...baseDirective(template, FiltersCtrl),
...{
bindToController: {
customers: '=',
regions: '=',
managers: '=',
projects: '=',
statuses: '=',
},
},
}
}
Now the issue is I'm able to run this app locally and also able to build the bundle files (app.bundle.js, vendor.bundle.js, manifest.bundle.js) but when I deploy these files to my test server, the console error is like below.
ReferenceError: production is not defined
at dispatchXhrRequest (vendor.bundle.js:24340)
at new Promise (<anonymous>)
at xhrAdapter (vendor.bundle.js:24325)
at dispatchRequest (vendor.bundle.js:92054)
at <anonymous>
vendor.bundle.js:65932
TypeError: Cannot read property 'map' of undefined
at https://#domain/cdn/3.2.1/vendor.bundle.js:5202:31
at https://#domain/cdn/3.2.1/vendor.bundle.js:5090:28
at f1 (https://#domain/cdn/3.2.1/vendor.bundle.js:5070:27)
at https://#domain/cdn/3.2.1/vendor.bundle.js:4920:35
at https://#domain/cdn/3.2.1/vendor.bundle.js:4920:35
at https://#domain/cdn/3.2.1/vendor.bundle.js:4920:35
at https://#domain/cdn/3.2.1/vendor.bundle.js:4672:27
at getAttributeFromProjects (https://#domain/cdn/3.2.1/app.bundle.js:117:10)
at MainController (https://#domain/cdn/3.2.1/app.bundle.js:127:21)
at invoke (https://#domain/cdn/3.2.1/vendor.bundle.js:58052:17) <div ui-view="" class="ng-scope">
My Traspiled app.bundle.js looks like below
webpackJsonp([1], {
/***/
101:
/***/
(function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony import */
var __WEBPACK_IMPORTED_MODULE_0_deepmerge__ = __webpack_require__(69);
/* harmony import */
var __WEBPACK_IMPORTED_MODULE_0_deepmerge___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_deepmerge__);
const baseConfig = {
title: 'Test Dashboard',
dashboard: {
title: 'Test Report',
subtitle: 'Weekly Highlights'
},
header: {
title: 'Company Confidential',
nav: 'Test'
}
}
let config = baseConfig
if (window.AppConfig) {
if (window.AppConfig.config) {
config = __WEBPACK_IMPORTED_MODULE_0_deepmerge___default.a(baseConfig, window.AppConfig.config)
}
}
const {
title,
dashboard,
header,
statusBar
} = config
/* harmony export (immutable) */
__webpack_exports__["c"] = title;
/* harmony export (immutable) */
__webpack_exports__["a"] = dashboard;
/* unused harmony export header */
/* unused harmony export statusBar */
/* harmony default export */
__webpack_exports__["b"] = (config);
/***/
}),
/***/
222:
/***/
(function(module, __webpack_exports__, __webpack_require__) {
"use strict";
/* harmony export (binding) */
__webpack_require__.d(__webpack_exports__, "b", function() {
return resolve;
});
/* harmony import */
var __WEBPACK_IMPORTED_MODULE_0_ramda__ = __webpack_require__(36);
/* harmony import */
var __WEBPACK_IMPORTED_MODULE_0_ramda___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_ramda__);
/* harmony import */
var __WEBPACK_IMPORTED_MODULE_1_angular__ = __webpack_require__(7);
/* harmony import */
var __WEBPACK_IMPORTED_MODULE_1_angular___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_1_angular__);
/* harmony import */
var __WEBPACK_IMPORTED_MODULE_2__utils__ = __webpack_require__(4);
/* harmony import */
var __WEBPACK_IMPORTED_MODULE_3__services_api__ = __webpack_require__(99);
/* harmony import */
var __WEBPACK_IMPORTED_MODULE_4__appConfig_config__ = __webpack_require__(101);
/* harmony import */
var __WEBPACK_IMPORTED_MODULE_5__dashboard_html__ = __webpack_require__(479);
/* harmony import */
var __WEBPACK_IMPORTED_MODULE_5__dashboard_html___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_5__dashboard_html__);
/* harmony reexport (default from non-hamory) */
__webpack_require__.d(__webpack_exports__, "c", function() {
return __WEBPACK_IMPORTED_MODULE_5__dashboard_html___default.a;
});
Which is very different from previous version of app.bundle.js which is on prod server which looks like below
webpackJsonp([1], {
/***/
10:
/***/
(function(module, exports, __webpack_require__) {
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.getWebpartData = undefined;
var _keys = __webpack_require__(124);
var _keys2 = _interopRequireDefault(_keys);
var _deepmerge = __webpack_require__(76);
var _deepmerge2 = _interopRequireDefault(_deepmerge);
var _utils = __webpack_require__(4);
var _majorMilestones = __webpack_require__(501);
var _majorMilestones2 = _interopRequireDefault(_majorMilestones);
var _budget = __webpack_require__(502);
var _budget2 = _interopRequireDefault(_budget);
var _projectRisksAndIssues = __webpack_require__(503);
var _projectRisksAndIssues2 = _interopRequireDefault(_projectRisksAndIssues);
var _actionItems = __webpack_require__(504);
var _actionItems2 = _interopRequireDefault(_actionItems);
var _keyDates = __webpack_require__(505);
var _keyDates2 = _interopRequireDefault(_keyDates);
var _gantt = __webpack_require__(506);
var _gantt2 = _interopRequireDefault(_gantt);
var _statusBar = __webpack_require__(507);
var _statusBar2 = _interopRequireDefault(_statusBar);
var _angular = __webpack_require__(6);
var _angular2 = _interopRequireDefault(_angular);
function _interopRequireDefault(obj) {
return obj && obj.__esModule ? obj : {
default: obj
};
}
below is my package.json file for reference
{
"name": "pmrdashboard",
"version": "3.2.1",
"dependencies": {
"#cgross/angular-notify": "2.5.1",
"angular": "1.4.2",
"angular-bootstrap": "~0.12.2",
"angular-chart.js": "^1.0.1",
"angular-gantt": "^1.2.13",
"angular-google-chart": "^0.1.0",
"angular-messages": "~1.4.2",
"angular-moment": "1.0.1",
"angular-pubsub": "^0.2.0",
"angular-resource": "~1.4.2",
"angular-sanitize": "~1.4.2",
"angular-strap": "^2.3.9",
"angular-toastr": "~1.5.0",
"angular-ui-router": "~0.2.15",
"animate.css": "~3.4.0",
"axios": "^0.16.2",
"babel-cli": "^6.24.1",
"babel-core": "^6.24.1",
"babel-polyfill": "^6.23.0",
"babel-runtime": "^6.23.0",
"bootstrap-sass": "3.3.7",
"chart.js": "2.1.0",
"deepmerge": "^1.3.2",
"echo-loader": "0.0.1",
"jquery": "~2.1.4",
"lodash": "^4.13.1",
"moment": "2.10.6",
"ngsticky-puemos": "^0.0.4",
"node-sass": "4.5.3",
"ramda": "^0.22.1"
},
"scripts": {
"dev": "babel-node scripts/cli.js dev",
"serve": "babel-node scripts/cli.js serve",
"build": "babel-node scripts/cli.js build --upload=false --plugins dynamic-import-node",
"deploy": "babel-node scripts/cli.js build",
"serve:prod": "babel-node scripts/cli.js serve:prod",
"serve:optimize": "babel-node scripts/cli.js serve:prod --optimize=true",
"serve:cdn": "babel-node scripts/cli.js serve:prod --usecdn=true"
},
"devDependencies": {
"babel-eslint": "^7.2.3",
"babel-loader": "^7.0.0",
"babel-plugin-angularjs-annotate": "^0.7.0",
"babel-plugin-dynamic-import-node": "^1.0.2",
"babel-plugin-external-helpers": "^6.22.0",
"babel-plugin-transform-object-rest-spread": "^6.23.0",
"babel-plugin-transform-runtime": "^6.23.0",
"babel-preset-env": "^1.5.1",
"chalk": "^1.1.3",
"clean-webpack-plugin": "0.1.16",
"cross-env": "^5.1.3",
"css-loader": "0.28.1",
"eslint": "2.13.1",
"eslint-config-angular": "^0.5.0",
"eslint-plugin-angular": "^2.4.0",
"execa": "^0.6.3",
"exports-loader": "0.6.4",
"express": "^4.15.3",
"extract-text-webpack-plugin": "2.1.0",
"file-loader": "0.11.1",
"fs-extra": "^3.0.1",
"html-loader": "0.4.5",
"html-webpack-harddisk-plugin": "0.1.0",
"html-webpack-plugin": "2.28.0",
"http-proxy-middleware": "*",
"http-server": "^0.10.0",
"image-webpack-loader": "3.3.1",
"imports-loader": "0.7.1",
"jshint-loader": "^0.8.4",
"raw-loader": "0.5.1",
"resolve-url-loader": "2.0.2",
"rollup": "^0.43.0",
"rollup-plugin-babel": "^2.7.1",
"rollup-plugin-node-resolve": "^3.0.0",
"sass-loader": "6.0.5",
"shelljs": "^0.7.7",
"ssh-webpack-plugin": "^0.1.7",
"style-loader": "0.17.0",
"svg-loader": "0.0.2",
"url-loader": "0.5.8",
"webpack": "3.0.0",
"webpack-dev-server": "^2.5.0",
"yargs": "^8.0.1"
},
"engines": {
"node": ">=0.10.0"
}
}
webpack config files: it's a folder with .babelrc, dev.js, server.js, prod.js, share.js and below is share.js file
const path = require('path')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const HtmlWebpackHarddiskPlugin = require('html-webpack-harddisk-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const {
rm
} = require('shelljs')
const pkg = require('../package.json')
const webpack = require('webpack')
const baseChunks = ['config', 'app']
const basePlugins = (chunks, enableHtml) => {
const html = enableHtml ?
[
new HtmlWebpackPlugin({
title: 'PMR Client',
filename: './index.html',
template: './src/client/index.ejs',
chunksSortMode: (a, b) => chunks.indexOf(a.names[0]) - chunks.indexOf(b.names[0]),
alwaysWriteToDisk: true,
env: process.env.NODE_ENV || 'development',
}),
new HtmlWebpackHarddiskPlugin(),
] :
[]
return [
new ExtractTextPlugin('style.css'),
...html,
new webpack.ProvidePlugin({
'window.jQuery': 'jquery',
}),
new webpack.optimize.ModuleConcatenationPlugin(),
]
}
const baseEntries = {
app: './src/app/index.js',
config: `./clients/${process.env.CLIENT}/config.js`,
}
const baseOutput = () => {
const output = {
path: path.join(__dirname, `../dist/cdn/${pkg.version}`),
filename: '[name].bundle.js',
}
if (process.env.NODE_ENV === 'production' && process.env.UPLOAD === 'true') {
output['publicPath'] = `//streamlinedoffice.com/pmr/cdn/${pkg.version}/`
}
return output
}
const sourceMap = (process.env.NODE_ENV === 'production') ? '' : 'sourceMap'
const getBaseConfig = ({
plugins = [],
chunks = [],
entries = baseEntries,
enableHtml = false
} = {}) => {
rm('-rf', path.resolve(__dirname, '../dist'))
const ch = [...baseChunks, ...chunks]
return {
entry: entries,
output: baseOutput(),
target: 'web',
devtool: 'cheap-module-eval-source-map',
plugins: [...basePlugins(ch, enableHtml), ...plugins],
module: {
rules: [{
test: /\.html$/,
use: [{
loader: 'html-loader',
options: {
minimize: true,
root: '../src/assets/images',
},
}, ],
},
{
test: [/src\/app.*\.js$/, /client.*\.js$/],
exclude: /node_modules/,
use: {
loader: 'babel-loader',
// loader:'echo-loader',
},
},
{
test: [/\.css$/, /\.scss$/],
use: ExtractTextPlugin.extract({
fallback: 'style-loader',
use: ['css-loader', `sass-loader?${sourceMap}`],
}),
},
{
test: /bootstrap-sass\/assets\/javascripts\//,
use: 'imports-loader?jQuery=jquery'
},
// Font Definitions
{
test: /\.svg$/,
loader: 'url-loader?limit=65000&mimetype=image/svg+xml&name=public/fonts/[name].[ext]',
},
{
test: /\.woff$/,
loader: 'url-loader?limit=65000&mimetype=application/font-woff&name=public/fonts/[name].[ext]',
},
{
test: /\.woff2$/,
loader: 'url-loader?limit=65000&mimetype=application/font-woff2&name=public/fonts/[name].[ext]',
},
{
test: /\.[ot]tf$/,
loader: 'url-loader?limit=65000&mimetype=application/octet-stream&name=public/fonts/[name].[ext]',
},
{
test: /\.eot$/,
loader: 'url-loader?limit=65000&mimetype=application/vnd.ms-fontobject&name=public/fonts/[name].[ext]',
},
{
test: /\.png$/,
use: {
loader: 'url-loader?limit=8192',
},
},
{
test: /\.(jpe?g|gif)$/i,
use: [
'file-loader?hash=sha512&digest=hex&publicPath=../&name=./img/[hash].[ext]',
{
loader: 'image-webpack-loader',
query: {
gifsicle: {
interlaced: false,
},
progressive: true,
optipng: {
optimizationLevel: 7,
},
bypassOnDebug: true,
},
},
],
},
],
},
}
}
module.exports = getBaseConfig
Below is the script used to build the app.bundle.js, vendor.bundle.js an d manifest.bundle.js files (this file is on scripts/cmds/prod.js)
import {
echo,
head,
execStrict,
ls,
copy,
rmdir,
mkdir
} from '../utils'
import fs from 'fs-extra'
import path from 'path'
import {
rollup
} from 'rollup'
import resolve from 'rollup-plugin-node-resolve'
import babel from 'rollup-plugin-babel'
const compiler = client =>
rollup({
entry: `./clients/${client}/config.js`,
plugins: [
resolve(),
babel({
exclude: 'node_modules/**',
babelrc: false,
presets: [
['env',
{
modules: false,
targets: {
browsers: [
"last 3 versions",
"Explorer 9",
],
},
},
],
],
plugins: ['external-helpers'],
externalHelpers: true
}),
],
}).then(bundle =>
bundle.write({
format: 'cjs',
dest: path.join(__dirname, `../../.tmpClients/${client}/config.js`),
})
)
const getClients = () =>
fs
.readdirSync('./clients')
.filter(file => fs.lstatSync(path.join('./clients', file)).isDirectory())
const handleCommand = async ({
upload = true,
optimize = true
}) => {
echo(head('Building clients...'))
const clients = getClients()
mkdir('./.tmpClients')
const promises = clients.map(client => {
compiler(client)
})
await Promise.all(promises)
echo(head('Run production build'))
await execStrict(
`cross-env UPLOAD=${upload} OPTIMIZE=${optimize} NODE_ENV=production webpack --config webpack/prod.js --progress --colors --define process.env.NODE_ENV="'production'"`
)
echo(head('Copying config files to clients'))
ls('./.tmpClients').forEach(client => {
copy({
origin: `./.tmpClients/${client}/*.js`,
dest: `./dist/clients/${client}`,
})
copy({
origin: `./dist/clients/${client}/index.html`,
dest: `./dist/clients/${client}/default.aspx`,
})
copy({
origin: './src/client/favicon.ico',
dest: `./dist/clients/${client}/`,
})
})
rmdir('./.tmpClients')
}
exports.command = 'build'
exports.describe = 'Create a production build'
exports.handler = handleCommand
exports.builder = {
upload: {
describe: 'Upload the production files to the cdn',
type: 'boolean',
default: true,
},
optimize: {
describe: 'Toggle the production optimizations, useful to check the production build as development',
type: 'boolean',
default: true,
},
}
below is .babelrc in webpack folder:
{
"presets": ["env"],
"plugins": ["transform-object-rest-spread", "dynamic-import-node"]
}
below .babelrc is in global same level as webpack folder
{
"presets": [
["env", {
"targets": {
"browsers": ["last 3 versions","Explorer 9"]
}
}]
],
"plugins": ["transform-runtime", "transform-object-rest-spread",
["angularjs-annotate", {
"explicitOnly": true
}]]
}
if anyone ran into such similar issue are know how to resolve it do share your inputs. Any help is much appreciated. Thanks

Angular Unit tests failing, not able to inject servies

this is my karma.conf.js
`use strict`;
var path = require('path');
var conf = require('./gulp/conf');
var _ = require('lodash');
var wiredep = require('wiredep');
var pathSrcHtml = [
path.join(conf.paths.src, '/**/*.html')
];
function listFiles() {
var wiredepOptions = wiredep({
directory: 'src/bower_components',
exclude: [],
dependencies: true,
devDependencies: true
});
return wiredep(wiredepOptions).js
.concat([
path.join(conf.paths.src, '/app/**/*.module.js'),
path.join(conf.paths.src, '/app/**/*.js'),
path.join(conf.paths.src, '/app/*.spec.js')
])
.concat(pathSrcHtml);
}
module.exports = function(config) {
var files=['https://maps.googleapis.com/maps/api/js?sensor=false'].concat(listFiles());
var configuration = {
files: files,
singleRun: true,
autoWatch: false,
ngHtml2JsPreprocessor: {
stripPrefix: conf.paths.src ,
moduleName: 'truelocal'
},
logLevel: 'WARN',
frameworks: ['jasmine', 'angular-filesort'],
angularFilesort: {
whitelist: [path.join(conf.paths.src, '/**/!(*.html|*.spec|*.mock).js')]
},
browsers : ['PhantomJS'],
plugins : [
'karma-phantomjs-launcher',
'karma-angular-filesort',
'karma-coverage',
'karma-jasmine',
'karma-ng-html2js-preprocessor'
],
coverageReporter: {
type : 'html',
dir : 'coverage/'
},
// level of logging
// possible values: config.LOG_DISABLE || config.LOG_ERROR || config.LOG_WARN || config.LOG_INFO || config.LOG_DEBUG
logLevel: config.LOG_DEBUG,
captureConsole: true,
reporters: ['progress']
};
// This is the default preprocessors configuration for a usage with Karma cli
// The coverage preprocessor in added in gulp/unit-test.js only for single tests
// It was not possible to do it there because karma doesn't let us now if we are
// running a single test or not
configuration.preprocessors = {};
pathSrcHtml.forEach(function(path) {
configuration.preprocessors[path] = ['ng-html2js'];
});
// This block is needed to execute Chrome on Travis
// If you ever plan to use Chrome and Travis, you can keep it
// If not, you can safely remove it
// https://github.com/karma-runner/karma/issues/1144#issuecomment-53633076
if(configuration.browsers[0] === 'Chrome' && process.env.TRAVIS) {
configuration.customLaunchers = {
'chrome-travis-ci': {
base: 'Chrome',
flags: ['--no-sandbox']
}
};
configuration.browsers = ['chrome-travis-ci'];
}
config.set(configuration);
};
//Bower.json
{
"name": "truelocal",
"version": "0.0.0",
"dependencies": {
"angular": "~1.4.10",
"angular-animate": "~1.4.10",
"angular-aria": "~1.4.10",
"angular-bootstrap": "~0.13.4",
"angular-cookies": "~1.4.10",
"angular-local-storage": "~0.2.3",
"angular-messages": "~1.4.10",
"angular-resource": "~1.4.10",
"angular-sanitize": "~1.4.10",
"angular-toastr": "~1.5.0",
"angular-touch": "~1.4.10",
"animate.css": "~3.4.0",
"bootstrap": "~3.3.5",
"jquery": "~1.11.3",
"malarkey": "yuanqing/malarkey#~1.3.1",
"moment": "~2.10.6",
"moment-parseformat": "~1.1.3",
"ng-file-upload-shim": "~9.1.2",
"jQuery.dotdotdot": "~1.7.4",
"lodash": "3.10.1",
"angular-ui-router": "~0.2.18",
"markerclustererplus": "~2.1.4",
"ng-fastclick": "~1.0.2",
"angular-swipe": "~0.1.0",
"angular-bindonce": "~0.3.3",
"angular-loading-bar": "~0.9.0",
"jquery-placeholder": "~2.3.1",
"angular-shims-placeholder": "^0.4.7"
},
"devDependencies": {
"angular-mocks": "~1.4.10"
},
"overrides": {
"bootstrap": {
"main": [
"dist/css/bootstrap.css",
"dist/fonts/glyphicons-halflings-regular.eot",
"dist/fonts/glyphicons-halflings-regular.svg",
"dist/fonts/glyphicons-halflings-regular.ttf",
"dist/fonts/glyphicons-halflings-regular.woff",
"dist/fonts/glyphicons-halflings-regular.woff2"
]
}
},
"resolutions": {
"jquery": "~1.11.3",
"angular": "^1.5.7"
}
}
This is an existing project with more than 200 Unit tests written, the code might need a bit of update but i'm not able to execute any unit test with dependent services.
I'm guessing the angular-mocks is causing an issue, if i move it up in the dependencies i dont get the module missing error. but i still dont get the other dependencies in the unit tests.
The Karma.conf.js was missing one file from the project. once all the files are fed to the test conf. tests worked like a Charm!

Failed to construct 'WebSocket': The URL '[object Object]' is invalid

I was trying to make a connection to the websocket and get the data in react router. The connection is not happening and getting error Uncaught SyntaxError: Failed to construct 'WebSocket': The URL '[object Object]' is invalid. in the browser console. Using npm start from the terminal to start the application. It is a simple react router application. Below is the react code where I think problem occurred.
import React from 'react'
export default React.createClass({
getInitialState: function() {
return { value : [],
client : '' };
},
componentWillMount: function() {
client = new WebSocket("ws://localhost:8000/","echo-protocol");
client.onerror = function() {
console.log('Connection Error');
};
client.onopen = function() {
function sendNumber() {
if (client.readyState === client.OPEN) {
var number = Math.round(Math.random() * 0xFFFFFF);
client.send(number.toString());
setTimeout(sendNumber, 1000);
}
}
sendNumber();
};
client.onmessage = function(e) {
this.setState({
value: e.data
});
}.bind(this);
},
componentWillUnmount: function(){
client.close();
},
render: function() {
return (React.createElement("div",null,this.state.value))
}
});
The webpack config file is -
module.exports = {
entry: './index.js',
output: {
filename: 'bundle.js',
publicPath: ''
},
module: {
loaders: [
{ test: /\.js$/, exclude: /node_modules/, loader: 'babel-loader?presets[]=es2015&presets[]=react' }
]
}
}
Also, the packge.json file is
{
"name": "react_form",
"version": "1.0.0",
"description": "Sample form that uses React for its rendering",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server --inline --content-base . --history-api-fallback"
},
"author": "J",
"license": "ISC",
"dependencies": {
"react": "^0.14.7",
"react-dom": "^0.14.7",
"react-router": "^2.0.0",
"websocket": "^1.0.23"
},
"devDependencies": {
"babel-core": "^6.5.1",
"babel-loader": "^6.2.2",
"babel-preset-es2015": "^6.5.0",
"babel-preset-react": "^6.5.0",
"http-server": "^0.8.5",
"webpack": "^1.12.13",
"webpack-dev-server": "^1.14.1"
}
}
If any other piece of code is required then please let me know. Also, please find the image of the error coming in the console on selecting the route option. What is the exact issue I am not able to get ?
Try this syntax:
const client = new WebSocket("ws://localhost:8000/");
I was debugging the app in various different ways I could. Then I found that there is no problem with the code. Further changed the name of the file from WebSocket to Socket and route name from webSocket to socket in various files and it worked. The problem was with naming the files and including them into the code accordingly.
On your backend side, if you dont have header with key = "Sec-WebSocket-Protocol" and value of one of your protocols, you will always get this error on chrome.
In my case, it was fine with Firefox

ESLint Parsing error: Unexpected token

I'm making an app with React JS and I use eslint.
But I'm getting this error
6:22 error Parsing error: Unexpected token ..
for the next code :
import {AUTH_USER, UNAUTH_USER} from '../actions/types';
export default function (state = {}, action) {
switch (action.type){
case AUTH_USER:
return { ...state, authenticated: true };
case UNAUTH_USER:
return { ...state, authenticated: false };
default:
return state;
}
}
.eslintrc file is as follows :
{
"parserOptions": {
"ecmaVersion": 6,
"sourceType": "module",
"ecmaFeatures": {
"jsx": true,
"experimentalObjectRestSpread": true
}
},
"plugins": [
"react"
],
"env": {
"es6": true,
"browser": true,
"node": true,
},
"rules": {
"quotes": 0,
"no-console": 1,
"no-debugger": 1,
"no-var": 1,
"semi": [1, "always"],
"no-trailing-spaces": 0,
"eol-last": 0,
"no-unused-vars": 0,
"no-underscore-dangle": 0,
"no-alert": 0,
"no-lone-blocks": 0,
"jsx-quotes": 1,
"react/display-name": [ 1, {"ignoreTranspilerName": false }],
"react/forbid-prop-types": [1, {"forbid": ["any"]}],
"react/jsx-boolean-value": 1,
"react/jsx-closing-bracket-location": 0,
"react/jsx-curly-spacing": 1,
"react/jsx-indent-props": 0,
"react/jsx-key": 1,
"react/jsx-max-props-per-line": 0,
"react/jsx-no-bind": 0,
"react/jsx-no-duplicate-props": 1,
"react/jsx-no-literals": 0,
"react/jsx-no-undef": 1,
"react/jsx-pascal-case": 1,
"react/jsx-sort-prop-types": 0,
"react/jsx-sort-props": 0,
"react/jsx-uses-react": 1,
"react/jsx-uses-vars": 1,
"react/no-danger": 1,
"react/no-did-mount-set-state": 1,
"react/no-did-update-set-state": 1,
"react/no-direct-mutation-state": 1,
"react/no-multi-comp": 1,
"react/no-set-state": 0,
"react/no-unknown-property": 1,
"react/prefer-es6-class": 1,
"react/prop-types": 0,
"react/react-in-jsx-scope": 1,
"react/require-extension": 1,
"react/self-closing-comp": 1,
"react/sort-comp": 1,
"react/wrap-multilines": 1
}
}
If I try without "experimentalObjectRestSpread": true in the ecmaFeatures in the eslintrc file I get the error.
When I with it I don't see error but it still won't work. I get something like
Any advice?
EDIT
The gulpfile.js is as follows :
'use strict';
var gulp = require('gulp');
var connect = require('gulp-connect');
var open = require('gulp-open');
var browserify = require('browserify');
var source = require('vinyl-source-stream');
var concat = require('gulp-concat');
var babelify = require('babelify');
var sass = require('gulp-sass');
var merge = require('merge-stream'); // Merge all styles (css, sass and less) in one big bundle
var lint = require("gulp-eslint");
var config = {
port: 8001,
devBaseUrl: 'http://localhost',
paths: {
html: "./src/*.html",
externals: "./src/assets/externals/*.js",
js: "./src/**/*.js",
images: './src/assets/images/**/*',
fonts: './src/assets/css/fonts/*',
css: ["./src/assets/css/*.css"],
sass: './src/assets/css/*.scss',
dist: "./dist",
mainJS: "./src/main.js"
}
};
gulp.task('connect', ['watch'], function () {
connect.server({
root: ['dist'],
port: config.port,
base: config.devBaseUrl,
livereload: true,
fallback: 'dist/index.html'
})
});
gulp.task('open', ['connect'], function () {
gulp.src('dist/index.html')
.pipe(open({uri: config.devBaseUrl + ":" + config.port + "/"}));
});
gulp.task('html', function () {
gulp.src(config.paths.html)
.pipe(gulp.dest(config.paths.dist))
.pipe(connect.reload());
});
gulp.task('externals', function () {
gulp.src(config.paths.externals)
.on('error', console.error.bind(console))
.pipe(concat('external.js'))
.pipe(gulp.dest(config.paths.dist + '/externals'))
.pipe(connect.reload());
});
gulp.task('js', function () {
browserify(config.paths.mainJS)
.transform('babelify', {presets: ['es2015', 'react']})
.bundle()
.on('error', console.error.bind(console))
.pipe(source('bundle.js'))
.pipe(gulp.dest(config.paths.dist + '/scripts'))
.pipe(connect.reload());
});
gulp.task('images', function () {
gulp.src(config.paths.images)
.pipe(gulp.dest(config.paths.dist + '/images'));
});
gulp.task('styles', function () {
var cssStyles = gulp.src(config.paths.css)
.pipe(concat('styles.css'));
var sassStyles = gulp.src(config.paths.sass)
.pipe(sass())
.pipe(concat('styles.scss'));
var mergedStream = merge(cssStyles, sassStyles)
.pipe(concat('bundle.css'))
.pipe(gulp.dest(config.paths.dist + '/css'))
.pipe(connect.reload());
return mergedStream;
});
gulp.task('fonts', function () {
gulp.src(config.paths.fonts)
.pipe(gulp.dest(config.paths.dist + '/css/fonts'));
});
gulp.task('lint', function () {
return gulp.src(config.paths.js)
.pipe(lint())
.pipe(lint.format());
});
gulp.task('watch', function () {
gulp.watch(config.paths.html, ['html']);
gulp.watch(config.paths.js, ['js', 'lint']);
gulp.watch(config.paths.externals, ['externals', 'lint']);
gulp.watch([config.paths.css, config.paths.sass], ['styles']);
gulp.watch(config.paths.images, ['images']);
});
gulp.task('default', ['html', 'js', 'styles', 'externals', 'images', 'fonts', 'lint', 'open', 'watch']);
And the package.json is as follows :
{
"name": "",
"version": "1.0.0",
"description": "",
"main": "index.js",
"dependencies": {
"react": "^15.1.0",
"react-dom": "^15.1.0",
"react-fontawesome": "^1.1.0",
"react-redux": "^4.4.5",
"react-router": "^2.4.1",
"react-slick": "^0.12.2",
"redux": "^3.5.2",
"redux-thunk": "^2.1.0"
},
"devDependencies": {
"babel-preset-es2015": "^6.9.0",
"babel-preset-react": "^6.5.0",
"babelify": "^7.3.0",
"browserify": "^13.0.1",
"eslint-plugin-react": "^5.1.1",
"gulp": "^3.9.1",
"gulp-browserify": "^0.5.1",
"gulp-concat": "^2.6.0",
"gulp-connect": "^4.0.0",
"gulp-eslint": "^2.0.0",
"gulp-open": "^2.0.0",
"gulp-sass": "^2.3.1",
"merge-stream": "^1.0.0",
"reactify": "^1.1.1",
"vinyl-source-stream": "^1.1.0"
},
"browserify": {
"transform": [
[
"reactify",
{
"es6": true
}
]
]
},
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC"
}
You need to install:
npm install --save-dev babel-plugin-transform-object-rest-spread
then add :
"plugins": ["transform-object-rest-spread"]
together with your presets.
See redux doc at the bottom of the page.
Since the object spread syntax is still a Stage 2 proposal for ECMAScript
you’ll need to use a transpiler such as Babel to use it in production.
You can use your existing es2015 preset, install
babel-plugin-transform-object-rest-spread and add it individually to
the plugins array in your .babelrc.
{ "presets": ["es2015"], "plugins":
["transform-object-rest-spread"] }
It is even easier with just using "experimentalObjectRestSpread": true in the ecmaFeatures section.
http://eslint.org/docs/user-guide/configuring#specifying-parser-options

React JS : Module Build Failuer, error showing in render colon

I am getting error like this
Module build failed: SyntaxError
It gives me error in colon of render function
Here it is my code :
webpack.config.js
module.exports = {
entry : './main.js',
output : {
path : './',
filename : 'index.js'
},
devServer : {
inline : true,
port : 3333
},
module : {
loaders : [
{
test : /\.js$/,
exclude : /node_modules/,
loader : 'babel',
query :{
presets : ['es2015', 'react']
}
}
]
}
package.json
{
"name": "library",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "webpack-dev-server"
},
"author": "",
"license": "ISC",
"dependencies": {
"babel": "^6.5.2",
"babel-core": "^6.9.0",
"babel-preset-es2015": "^6.9.0",
"babel-preset-react": "^6.5.0",
"react": "^15.0.2",
"react-dom": "^15.0.2"
},
"devDependencies": {
"babel": "^6.5.2",
"babel-core": "^6.9.0",
"babel-loader": "^5.3.2"
}
main.js
import React from 'react';
import ReactDom from 'react-dom';
var Heading = React.createClass({
render : function() {
return <th>{this.props.heading}</th>;
}
});
var Headings = React.createClass({
render : function(){
var headings = this.props.headings.map(function(heading) {
return(<Heading heading = {name}/>);
});
return (<thead><tr>{headings}</tr><thead>);
}
});
var Row = React.createClass({
render : function() {
return (
<tr>
<td>{this.props.changeSet.when}</td>
<td>{this.props.changeSet.who}</td>
<td>{this.props.changeSet.description}</td>
</tr>
);
}
});
var Rows = React.createClass({
render : function() {
var rows = this.props.changeSets.map(function(changeSet) {
return(<Row changeSet = {changeSet} />);
});
return <tbody>{rows}</tbody>;
}
});
var App = React.createClass({
render : function() {
return (
<table className='table'>
<Headings headings={this.props.headings} />
<Rows changeSets={this.props.changeSets} />
</table>
);
}
});
/* Data Declaration */
var data = [
{
"when": "2 minutes ago",
"who": "Jill Dupre",
"description": "Created new account"
},
{
"when": "1 hour ago",
"who": "Lose White",
"description": "Added fist chapter"
},
{
"when": "2 hours ago",
"who": "Jordan Whash",
"description": "Created new account"
}
];
var headings = ['When','Who', 'Description'];
/* Call to Render Function for entire app */
ReactDom.render(<App headings={headings} changeSets={data} />, document.getElementById('container'));
Can somebody please provide a solution for it. I have included babel-core also but can't figure out what's wrong.
I tried setting up your code locally and was able to resolve the issue.
I was getting a Module build failed: ReferenceError: [BABEL] - path to file error
The reason is, The node API for babel has been moved to babel-core.So remove the babel dependency from both dependencies and devDependencies, move the babel-loader to your dependencies and clear the devDependencies of your package.json file and reinstall your modules. It should work
There are some syntax errors on
line 20 render : function(){
unclosed tags in line 15 return (<thead><tr>{headings}</tr><thead>);

Resources