Webpack dev server run on different port - angularjs

So I have IIS serving up my WebApi and AngularJS project on port 80, using a the alias mywebsite.local-dev.com in the hosts file.
I have webpack config setup for bundling, all I want to do now is stick webpack dev server over the top so that when I modify a file it re bundles everything and updates the browser.
I have browser-sync nearly working but require('./somehtmltemplate.html') seems to be causing issues. It's an Angular app so I use require in the ui-router template property. Here is my gulpfile:
var gulp = require('gulp'),
browserSync = require('browser-sync').create(),
watch = require('gulp-watch'),
webpack = require('webpack'),
webpackconfig = require('./webpack.config');
gulp.task("webpack", function(callback) {
// run webpack
webpack(
webpackconfig,
function(err, stats) {
if(err) throw new gutil.PluginError("webpack", err);
callback();
}
);
});
gulp.task('watch', function() {
browserSync.init({
proxy: "mywebsite.local-dev.com"
});
gulp.watch("App/**/*.js", ['webpack']).on('change', browserSync.reload);
gulp.watch("App/**/*.html", ['webpack']).on('change', browserSync.reload);
});
My question is, how do I get either one working.
edit
Because I am using .cshtml I can't use webpack-dev-server. So the question is, how can I get gulp working?

I solved a similar problem by having Browsersync proxy my external server (MAMP in my case, but it shouldn't matter) while using webpack-dev-middleware and webpack-hot-middleware as middleware on the proxy. With that setup, you can have your normal server take care of serving your app, and Browsersync+Webpack will just handle asset bundling & serving, and browser injections & reloads.
Here's a working example if you're interested: github.com/shanecav/webpack-browsersync-proxy

Related

Setting environment for AngularJS development with existing OSGi/Rest serverices

How to setup the dev environment where the UI is to be re-done using AngularJS and typescript etc but we already have an existing set of services hosted in rest/osgi bundles.
All the development models with AngularJS and type script talks about node/npm etc but how do we hit existing services with that? do i need to enable cors etc for development?
how is UI development done in these kind of projects as i believe not all projects are done from the beginning and have liberty to use node at server.
Well, usually from an angular app you define some kind of angular service that talks to your api in a standard way.
It's true that most "Frontend" projects use a mocking server during development but it isn't hard to hard to use a real server for this, provided it's not you own production server, obviously.
About the cors issue, I use to let CORS fully open during development ,and have a minimally accesable configuration on production, depending on your project.
After some research we have finalized the DevEnv and it's working out very well.
used angular cli for development
used proxy server to make the calls made to 4200 port to redirect to express server running at port 3000
package.json:
"start": "ng serve --proxy-config proxy.conf.json",
finally wrote a small express server to login to existing server and then pipe all requests!
This was our code:
var app = express();
//enable cors
var cors = require('cors')
app.use(cors());
//relay all calls to osgi server!!
app.use('/a/b/c/rest', function (req, res) {
var apiServerHost = "https://" + HOST + ":" + PORT + "/a/b/c/rest";
try {
var url = apiServerHost + req.url;
req.pipe(request(
{
headers: headers,
url: url,
"rejectUnauthorized": false
})).pipe(res);
} catch (error)
{
console.log("Error " + error);
}
} // Added by review
No mock required

How to add my own server code to webpack-dev-server execution

Basic question about how to add my own server-based code to webpack-dev-server, or alternatively, replace webpack-dev-server with express (giving up hot module reloading). I expected to find a file called something like server.js, that I can add my own code to. This is a basic question, as every non-static application needs their own server code, but I haven't found a straight forward way of doing it. I'm using Angular 2 Webpack Starter. I would expect it to be easy to subsequently drop webpack-dev-server for straight express when going to production.
You can still use Express and have hot reloading, by using webpack-dev-middleware and webpack-hot-middleware.
Both middleware should not be loaded in production, for which you can use something like this:
// Webpack (when not running in production mode)
if (process.env.NODE_ENV !== 'production') {
const webpackDevMiddleware = require('webpack-dev-middleware');
const webpackHotMiddleware = require('webpack-hot-middleware');
const webpackConfig = require('./webpack.config');
const compiler = require('webpack')(webpackConfig);
app.use(webpackDevMiddleware(compiler, {
noInfo : true,
publicPath : webpackConfig.output.publicPath
}));
app.use(webpackHotMiddleware(compiler));
}
(app is an Express instance)

Angular apps break when run in Electron

I started building an Electron app and I am encountering some issues when I try to run an angular distribution inside.
For the angular app I'm using yeoman and grunt for building. If I develop the angular app with grunt serve and running it on localhost:9000, the Electron app can pick the application up just fine. However, if I run grunt build and I point the Electron app to the static files I get some angular errors.
[$injector:modulerr] Failed to instantiate module clientApp due to:
Error: [$injector:modulerr] Failed to instantiate module ngResource due to:
Error: [$injector:nomod] Module 'ngResource' is not available! You either
misspelled the module name or forgot to load it. If registering a module
ensure that you specify the dependencies as the second argument.
In the electron app Im running a server with express and I also tried to pick run the angular app through express at localhost:8000. That didn't work either. I also tried to run another angular app that it's deployed on my server and working just fin in the browser - didn't work in Electron. Same errors on all the tries.
I also have to mention that in all cases, if I open the angular app in the browser it works fine.
This is the electron code:
app.on('ready', function() {
// Create the browser window.
mainWindow = new BrowserWindow({width: 1024, height: 764, title: "uMaster"});
// and load the index.html of the app.
var url = path.join(__dirname, "dist", "index.html");
url = "file://" + url;
console.log(url);
// mainWindow.loadURL(url); ---- this is not working in Electron
// mainWindow.loadURL("http://localhost:8000"); -- not working when served by express
mainwindow.loadURL("http://localhost:9000"); // working when angular runs with grunt serve
// Emitted when the window is closed.
mainWindow.on('closed', function() {
// Dereference the window object, usually you would store windows
// in an array if your app supports multi windows, this is the time
// when you should delete the corresponding element.
mainWindow = null;
});
/* ----------------------- */
});
Fixed this problem by initialising electron's BrowserWindow with nodeIntegration: false
mainWindow = new BrowserWindow({width: 1024, height: 764, title: "app", webPreferences: {"nodeIntegration":false}});
Your answer is correct. If you want to mantain node integration you can also use this code in your index.html, before loading any other script:
<script>
window.nodeRequire = require;
delete window.require;
delete window.exports;
delete window.module;
</script>

AngularJS better way to read config file?

I built a angularJS app that I wanted dynamically configured, so I created a config.json file with the needed configurations, and decided to load the config file in app.config as such:
angular.module("myapp",[]).config([ my injections] , function(my providers){
if (window.XMLHttpRequest) {
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
xhr.open("GET","config.json"); //my config file
xhr.send();
xhr.onreadystatechange=function()
{
if (xhr.readyState==4 && xhr.status==200)
{
//config file parsed, set up params
}
}
})
The reason I am doing it this way is because $http is not injected in config state, and I do not want to "configure" the app at a controller level.
The application works fine. it does what I want to do, and everything works great...EXCEPT when it comes to unit testing (with karma + jasmine).
even though in karma.conf i have:
{pattern: 'config.json',served:true,watched:false,included:false}
defined, when I launch karma, I get a cli [WARN] about config.json 404. and my unit tests to see if everything is configured, fails (i.e it didnt read config.json)
Is there a better way to write config files for unit testing?
In our apps we have external file config.js, which contains just ordinary module which provides constants with configuration.
angular.module('myAppPrefixconfig')
.constant('PLAIN_CONSTANT', 'value'),
.constant('APP_CONFIG', {...});
In your app you have dependancy on it, and there is ordinary http request - which can be resolved by your backend with proper configuration.
In Karma tests you can then provide 'testing config' directly in karma.conf.

Configuring Yeoman for building non-root projects

I might be missing something obvious, but i really can't figure it out by going over the docs and issues on GitHub -
I'm developing an AngularJS project that will be deployed on a specific sub-directory on the server (i.e not the root).
I'm using Yeoman.io, and trying to configure it so the app is self-contained and doesn't rely on absolute paths like '/images' and so on.
Every attempt to mess around with the Grunt file or Compass config ends up with a broken build. Paths of images and sprites are wrong - sometimes it's a wrong directory and sometimes wrong filename (no revision prefixes).
Anyone had good experience with that?
So if I understand you correctly, you want to serve your angular project on a specific path on system.
In grunt.js, I've registered a server task which starts my (local) server:
grunt.registerTask('server', 'Start server', function() {
var done = this.async();
var app = require('./app.js');
var http = require('http');
// Start server
http.createServer(app).listen(app.get('port'), function () {
console.log("Express server listening on port " + app.get('port'));
}).on('close', done);
});
app.js contains the server config:
var express = require('express'),
path = require('path');
var app = module.exports = express();
// Configuration
app.configure(function () {
app.set('port', process.env.PORT || 4000);
app.use(express['static'](path.join(__dirname, 'dist')));
});
In my example I serve the project on directory dist, but this can be anything.

Resources