Angular 2 import error with RequireJS - asp.net

I'm unable to import Angular2/core due to the following error:
Module name "angular2/core" has not been loaded yet for context: _. Use require([])
This is my Typescript file:
import {Component, View} from "angular2/core";
import {bootstrap} from "angular2/platform/browser";
#Component({
selector: "menu"
})
class MenuComponent {
isActive(path: string) {
return true
}
}
bootstrap(MenuComponent);
Which is compiled with this configuration:
{
"compilerOptions": {
"noImplicitAny": false,
"noEmitOnError": true,
"removeComments": true,
"sourceMap": true,
"target": "es5",
"module": "commonjs",
"outDir": "../wwwroot/js",
"experimentalDecorators": true,
"emitDecoratorMetadata": true
},
"exclude": [
"node_modules",
"wwwroot"
]
}
This is the compiled Javascript file:
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var core_1 = require("angular2/core");
var browser_1 = require("angular2/platform/browser");
var MenuComponent = (function () {
function MenuComponent() {
}
MenuComponent.prototype.isActive = function (path) {
var page = window.location.pathname;
if (path === undefined || path === '') {
path = '';
}
var result = path === '' ? path === page[page.length - 1] : page[page.length - 1].indexOf(path) > -1;
return result;
};
MenuComponent = __decorate([
core_1.Component({
selector: "menu"
}),
__metadata('design:paramtypes', [])
], MenuComponent);
return MenuComponent;
})();
browser_1.bootstrap(MenuComponent);
//# sourceMappingURL=menu.js.map
My javascript is imported in this order:
<script type="text/javascript" src="~/lib/requirejs/require.js"></script>
<script type="text/javascript" src="~/lib/angular2-polyfills.js"></script>
<script type="text/javascript" src="~/lib/es6-shim.js"></script>
<script type="text/javascript" src="~/lib/system-polyfills.js"></script>
<script type="text/javascript" src="~/lib/angular2-polyfills.js"></script>
<script type="text/javascript" src="~/lib/system.src.js"></script>
<script type="text/javascript" src="~/lib/rx.js"></script>
<script type="text/javascript" src="~/lib/angular2.js"></script>
<script type="text/javascript" src="~/js/menu.js"></script>
I was wondering what's causing the above error. Since I'm unable to change the Javascript code which is compiled from the Typescript file.
I'm also using Visual Studio 2015 with ASP.Net 5.
I know Angular 2 is still in beta and ASP.Net 5 is still in RC, but I doubt this combination is causing the issue.
Thanks for the help.

I think that you use two module loaders, RequireJS and SystemJS. See what you included in your HTML file:
<script type="text/javascript" src="~/lib/requirejs/require.js"></script> <------
<script type="text/javascript" src="~/lib/angular2-polyfills.js"></script>
<script type="text/javascript" src="~/lib/es6-shim.js"></script>
<script type="text/javascript" src="~/lib/system-polyfills.js"></script>
<script type="text/javascript" src="~/lib/angular2-polyfills.js"></script>
<script type="text/javascript" src="~/lib/system.src.js"></script> <------
<script type="text/javascript" src="~/lib/rx.js"></script>
<script type="text/javascript" src="~/lib/angular2.js"></script>
<script type="text/javascript" src="~/js/menu.js"></script>
You only need one. For example SystemJS. That's the reason of the message. Both libraries try to load the angular2/core module...
Edit
If you want to use SystemJS only, you could update your tsconfig.json file:
{
"compilerOptions": {
"noImplicitAny": false,
"noEmitOnError": true,
"removeComments": true,
"sourceMap": true,
"target": "es5",
"module": "system", <--------
"moduleResolution": "node", <--------
"outDir": "../wwwroot/js",
"experimentalDecorators": true,
"emitDecoratorMetadata": true
},
"exclude": [
"node_modules",
"wwwroot"
]
}
Hope it helps you,
Thierry

Related

Gulp and Critical CSS - TypeError: Cannot read property 'content-type' of undefined

I'm running my build in Gulp and keep getting the following error in my terminal when it comes to generating my critical css files.
[08:47:29] -> Generating critical CSS: https://example.com/ -> ./templates/index_critical.min.css
[08:47:43] TypeError: Cannot read property 'content-type' of undefined
What does the error mean?
How do I solve the error?
If this is a syntax issue in my gulp file - is there way to find the line and reference to the issue either in the terminal when running the command or by using a validator?
Below is the gulp task for the critical css along with the tasks for processing the css and sass files which it references.
// scss - build the scss to the build folder, including the required paths, and writing out a sourcemap
gulp.task("scss", () => {
$.fancyLog("-> Compiling scss");
return gulp.src(pkg.paths.src.scss + pkg.vars.scssName)
.pipe($.plumber({errorHandler: onError}))
.pipe($.sourcemaps.init({loadMaps: true}))
.pipe($.sass({
includePaths: pkg.paths.scss
})
.on("error", $.sass.logError))
.pipe($.cached("sass_compile"))
.pipe($.autoprefixer())
.pipe($.sourcemaps.write("./"))
.pipe($.size({gzip: true, showFiles: true}))
.pipe(gulp.dest(pkg.paths.build.css));
});
// css task - combine & minimize any distribution CSS into the public css folder, and add our banner to it
gulp.task("css", ["scss"], () => {
$.fancyLog("-> Building css");
return gulp.src(pkg.globs.distCss)
//.pipe(purgecss({
// content: [pkg.paths.templates + '*.twig']
// }))
.pipe($.plumber({errorHandler: onError}))
.pipe($.newer({dest: pkg.paths.dist.css + pkg.vars.siteCssName}))
.pipe($.print())
.pipe($.sourcemaps.init({loadMaps: true}))
.pipe($.concat(pkg.vars.siteCssName))
.pipe($.if(process.env.NODE_ENV === "production",
$.cssnano({
discardComments: {
removeAll: true
},
discardDuplicates: true,
discardEmpty: true,
minifyFontValues: true,
minifySelectors: true
})
))
.pipe($.header(banner, {pkg: pkg}))
.pipe($.sourcemaps.write("./"))
.pipe($.size({gzip: true, showFiles: true}))
.pipe(gulp.dest(pkg.paths.dist.css))
.pipe($.filter("**/*.css"))
.pipe($.livereload());
});
// Process the critical path CSS one at a time
function processCriticalCSS(element, i, callback) {
const criticalSrc = pkg.urls.critical + element.url;
const criticalDest = pkg.paths.templates + element.template + "_critical.min.css";
let criticalWidth = 1200;
let criticalHeight = 1200;
if (element.template.indexOf("amp_") !== -1) {
criticalWidth = 600;
criticalHeight = 19200;
}
$.fancyLog("-> Generating critical CSS: " + $.chalk.cyan(criticalSrc) + " -> " + $.chalk.magenta(criticalDest));
$.critical.generate({
src: criticalSrc,
dest: criticalDest,
penthouse: {
blockJSRequests: false,
forceInclude: pkg.globs.criticalWhitelist
},
inline: false,
ignore: [],
css: [
pkg.paths.dist.css + pkg.vars.siteCssName,
],
minify: true,
width: criticalWidth,
height: criticalHeight
}, (err, output) => {
if (err) {
$.fancyLog($.chalk.magenta(err));
}
callback();
});
}
// critical css task
gulp.task("criticalcss", ["css"], (callback) => {
doSynchronousLoop(pkg.globs.critical, processCriticalCSS, () => {
// all done
callback();
});
});
// Lean Production build
gulp.task("leanbuild", ["set-prod-node-env", "static-assets-version", "criticalcss"]);
This happens if the src param you pass into critical is invalid, and returns no response.

How to choose between rtl css file generated by rtl css and ltr css

We're building a website for a customer and the customer demands both an english and an arabic version of the website.
We're using infernojs#7 with webpack#4 and we're bundling css using webpack as well.
We're applying https://github.com/nicolashemonic/rtl-css-transform-webpack-plugin so that we get two versions of our output css file : RTL version and LTR version, our filenames are hashed for caching obviously.
Here is the Problem : how to choose at runtime between the rtl css file and ltr css file when we don't know their name(because of the hash) ?
I'm thinking of using react-helmet in root component to do something like
<link rel="stylesheet" href={this.state.lang==='ar' ? 'bunldename.rtl.css' : 'bundlename.css'}/>
<!-- we'll actually get lang from route but that's not the point-->
My only problem is getting the bundlename, I thought of using DefinePlugin but I couldn't get bundlename even in webpack.config.js.
Here is my webpack config:
const HtmlWebpackPlugin = require('html-webpack-plugin'),
RtlCssPlugin = require('rtl-css-transform-webpack-plugin'),
ExtractCssChunks = require('extract-css-chunks-webpack-plugin'),
HtmlWebpackExcludeAssetsPlugin = require('html-webpack-exclude-assets-plugin'),
path = require('path');
const commonPlugins = [
new ExtractCssChunks({
'filename': 'css/[name].[contenthash].css'
}),
new RtlCssPlugin({
filename: 'css/[name].[hash].rtl.css'
}),
new HtmlWebpackPlugin({
'title': 'mytitle',
'template': 'index.html',
excludeAssets: /\.css/u
}),
new HtmlWebpackExcludeAssetsPlugin()
];
const productionPlugins = [
...
];
module.exports = (_env,argv) => ({
'entry': './src/index.jsx',
'output': {
'path': path.resolve('../public'),
'filename': 'js/main.[contenthash].js'
},
'plugins': argv.mode === 'development' ? commonPlugins : [...commonPlugins,...productionPlugins],
'module': {
'rules': [
{
'test': /\.(js|jsx)$/u,
'use':
{
'loader': 'babel-loader',
'options': {
'presets': ['#babel/preset-env'],
'plugins': [['babel-plugin-inferno', { 'imports': true }]]
}
}
},
{
'test': /\.css$/u,
'use': [ExtractCssChunks.loader, 'css-loader']
}
]
},
'devServer': {
'host': '0.0.0.0',
'historyApiFallback': true,
'contentBase': './public',
'publicPath': 'http://localhost:8080/'
},
'resolve': {
'alias': {
'inferno': (argv.mode === 'development')
? 'inferno/dist/index.dev.esm.js'
: 'inferno/dist/index.esm.js',
'react': 'inferno-compat',
'react-dom': 'inferno-compat'
}
}
});

Using express-handlebars with Cytoscape.js

Hi I'm new to web development and I'm trying to play around with Cytoscape.js. I decided to use Node.js, Express, and Express-handlebars to run my webpage. I wanted to use Cytoscape.js to display a graph however I'm not sure how to use handlebars to get a reference to the container to initialize the cytoscape object.
Here's my main.handlebars file:
<!doctype html>
<html>
<head>
<title>Hello Cytoscape</title>
</head>
<body>
{{{body}}}
</body>
</html>
Here's my home.handlebars file:
<div id="cy"></div>
Here's my .js file:
/**
*
*/
'use strict';
var express = require('express');
var app = express();
var cytoscape = require('cytoscape');
//layout defaults to main, located in the views layout folder
var handlebars = require('express-handlebars').create({defaultLayout:'main'});
app.use(express.static('public'));
//sets the template engine to use for the express object
//a template engine will implement the view part of the app
app.engine('handlebars', handlebars.engine);
app.set('view engine', 'handlebars');
//initialize the cytoscape object
var cy = cytoscape({
//<----not sure how to do this----->
container: document.getElementById('cy'), // container to render in
elements: [ // list of graph elements to start with
{ // node a
data: { id: 'a' }
},
{ // node b
data: { id: 'b' }
},
{ // edge ab
data: { id: 'ab', source: 'a', target: 'b' }
}
],
style: [ // the stylesheet for the graph
{
selector: 'node',
style: {
'background-color': '#666',
'label': 'data(id)'
}
},
{
selector: 'edge',
style: {
'width': 3,
'line-color': '#ccc',
'target-arrow-color': '#ccc',
'target-arrow-shape': 'triangle'
}
}
],
layout: {
name: 'grid',
rows: 1
},
// initial viewport state:
zoom: 1,
pan: { x: 0, y: 0 },
// interaction options:
minZoom: 1e-50,
maxZoom: 1e50,
zoomingEnabled: true,
userZoomingEnabled: true,
panningEnabled: true,
userPanningEnabled: true,
boxSelectionEnabled: false,
selectionType: 'single',
touchTapThreshold: 8,
desktopTapThreshold: 4,
autolock: false,
autoungrabify: false,
autounselectify: false,
// rendering options:
headless: false,
styleEnabled: true,
hideEdgesOnViewport: false,
hideLabelsOnViewport: false,
textureOnViewport: false,
motionBlur: false,
motionBlurOpacity: 0.2,
wheelSensitivity: 1,
pixelRatio: 'auto'
});
app.get('/', function (req, res) {
var context = {};
res.render('home', context);
});
//listener all for unrecognized urls
//return 404 not found response
app.use(function(req,res){
res.status(404);
res.render('404');
});
//listener for errors generate on server
//return 500 response
app.use(function(err, req, res, next){
console.error(err.stack);
res.type('plain/text');
res.status(500);
res.render('500');
});
if (module === require.main) {
// [START server]
// Start the server
var server = app.listen(process.env.PORT || 8080, function () {
var port = server.address().port;
console.log('App listening on port %s', port);
});
// [END server]
}
module.exports = app;
So I guess my question is how do I get a reference to the div container id="cy" to initialize my Cytoscape.js graph using express-handlebars, thanks in advance for any help.
If you run Cytoscape on the serverside -- as you're doing in your example -- then it's not running and not shown on the clientside.
Unless you're doing serverside-only graph analysis, you should be using Cytoscape on the clientside. Your page (main.handlebars) is the driver of everything clientside, so put your Cytoscape code there. Or in the page, reference your Cytoscape code with a <script> tag.

e2e browser opens and close immedietly

I am trying to test my app and followed this link http://lathonez.github.io/2016/ionic-2-e2e-testing/ i merged my app with firebase. Everything worked good, but when i run npm run e2e browser opens and close immediately in my terminal pops an error.
I followed this link http://lathonez.github.io/2016/ionic-2-e2e-testing/
Actually my issue is that i could not able to see any action takes place in my e2e browser could some on help me
protractorconfig.js
exports.config = {
baseUrl: 'http://192.168.1.2:8100/',
specs: [
'../app/pages/home/home.e2e.ts',
'../app/pages/Admin/admin.e2e.ts',
//'../app/pages/Listing/lisitngPage.e2e.ts'
],
exclude: [],
framework: 'jasmine2',
allScriptsTimeout: 110000,
jasmineNodeOpts: {
showTiming: true,
showColors: true,
isVerbose: false,
includeStackTrace: false,
defaultTimeoutInterval: 400000
},
directConnect: true,
chromeOnly: true,
capabilities: {
'browserName': 'chrome',
'chromeOptions': {
'args': ['--disable-web-security']
}
},
onPrepare: function() {
var SpecReporter = require('jasmine-spec-reporter');
jasmine.getEnv().addReporter(new SpecReporter({displayStacktrace: true}));
browser.ignoreSynchronization = false;
},
useAllAngular2AppRoots: true
};
gulpfile.ts
import { join } from 'path';
const config: any = {
gulp: require('gulp'),
appDir: 'app',
testDir: 'test',
testDest: 'www/build/test',
typingsDir: 'typings',
};
const imports: any = {
gulp: require('gulp'),
runSequence: require('run-sequence'),
ionicGulpfile: require(join(process.cwd(), 'gulpfile.js')),
};
const gulp: any = imports.gulp;
const runSequence: any = imports.runSequence;
// just a hook into ionic's build
gulp.task('build-app', (done: Function) => {
runSequence(
'build',
(<any>done)
);
});
// compile E2E typescript into individual files, project directoy structure is replicated under www/build/test
gulp.task('build-e2e', ['clean-test'], () => {
let typescript: any = require('gulp-typescript');
let tsProject: any = typescript.createProject('tsconfig.json');
let src: Array<any> = [
join(config.typingsDir, '/index.d.ts'),
join(config.appDir, '**/*e2e.ts'),
];
let result: any = gulp.src(src)
.pipe(typescript(tsProject));
return result.js
.pipe(gulp.dest(config.testDest));
});
// delete everything used in our test cycle here
gulp.task('clean-test', () => {
let del: any = require('del');
// You can use multiple globbing patterns as you would with `gulp.src`
return del([config.testDest]).then((paths: Array<any>) => {
console.log('Deleted', paths && paths.join(', ') || '-');
});
});
// run jasmine unit tests using karma with PhantomJS2 in single run mode
gulp.task('karma', (done: Function) => {
let karma: any = require('karma');
let karmaOpts: {} = {
configFile: join(process.cwd(), config.testDir, 'karma.config.js'),
singleRun: true,
};
new karma.Server(karmaOpts, done).start();
});
// run jasmine unit tests using karma with Chrome, Karma will be left open in Chrome for debug
gulp.task('karma-debug', (done: Function) => {
let karma: any = require('karma');
let karmaOpts: {} = {
configFile: join(process.cwd(), config.testDir, 'karma.config.js'),
singleRun: false,
browsers: ['Chrome'],
reporters: ['mocha'],
};
new karma.Server(karmaOpts, done).start();
});
// run tslint against all typescript
gulp.task('lint', () => {
let tslint: any = require('gulp-tslint');
return gulp.src(join(config.appDir, '**/*.ts'))
.pipe(tslint())
.pipe(tslint.report('verbose'));
});
// build unit tests, run unit tests, remap and report coverage
gulp.task('unit-test', (done: Function) => {
runSequence(
['lint', 'html'],
'karma',
(<any>done)
);
});

angular ui-router importing css

I want to load css on demand but I don't get it.
This is the file structure
index.html
<script src="js/ui-router-styles.js"></script>
<script src="js/app.js"></script>
<script src="js/dao.js"></script>
<script src="js/controllers.js"></script>
....
</head>
<body ng-app="starter" ui-router-styles>
<div ui-view></div>
</body>
app.js
var my_app = angular.module('starter', ['starter.posicion_integrada', 'uiRouterStyles','ionic','pascalprecht.translate']);
config part
my_app.config(function($stateProvider, $urlRouterProvider, $ionicConfigProvider) {
$ionicConfigProvider.backButton.previousTitleText(false);
$ionicConfigProvider.backButton.text('');
$stateProvider
.state('app', {
url: '/app',
abstract: true,
templateUrl: 'views/menu.html',
controller: 'appController'
})
.state('app.CarrouselSearcher', {
url: '/CarrouselSearcher/:entUsuario/:codUsuario',
views: {
'menuContent': {
templateUrl: 'views/carrouselSearcher.html',
controller: 'carrouselsearcherCtrl',
data: {
css: ['css/tabla.css', 'css/carousel.css']
}
}
}
})
I found a problem of your code in ui-router-styles.js
is
for(var state = toState; state && state.name !== ''; state=$$parentState(state)) {
if(state && state.data && state.data.css) {
if(!Array.isArray(state.data.css)) {
state.data.css = [state.data.css];
}
angular.forEach(state.data.css, function(css) {
// css = {name: 'layout', href: '/layout.css'}
if(typeof css === 'object' && css.name && css.href && !stylesObject[css.name]) {
stylesObject[css.name] = css.href;
}else if(typeof css === 'string') {
stylesObject[css] = css;
}
});
in your
.state('app.CarrouselSearcher',
your data.css is in another object
state.current.views.menuContent.data.css;
// this condition checks just state.data.css
if(state && state.data && state.data.css) {
your css are in views.menuContent then data.css
so this directive cant finds css from multiple views

Resources