0

I am trying to use a typescript class in js. But could not find it in js code. I can use it in typescript but not in the javascript.

animal.ts

export class Animal {

    name:string;    

    constructor(name:string) {
        this.name=name;
    }

    public run(){
        console.log(this.name+':Animal runs.');
    }

    public eat(){
        console.log(this.name+':Animal eats.');
    }

    public sleep(){
        console.log(this.name+':Animal sleeps.');
    }
}

//TEST 
let mouse:Animal = new Animal("Alfred");
let cat:Animal = new Animal("Gustavo");

if(mouse !=null && cat!=null){
    mouse.run();
    cat.sleep();
}else{
    console.log("ERROR cat or mouse  NULL");
}

animal.js

(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
"use strict";
var Animal = (function () {
    function Animal(name) {
        this.name = name;
    }
    Animal.prototype.run = function () {
        console.log(this.name + ':Animal runs.');
    };
    Animal.prototype.eat = function () {
        console.log(this.name + ':Animal eats.');
    };
    Animal.prototype.sleep = function () {
        console.log(this.name + ':Animal sleeps.');
    };
    return Animal;
}());
exports.Animal = Animal;
//TEST 
var mouse = new Animal("Alfred");
var cat = new Animal("Gustavo");
if (mouse != null && cat != null) {
    mouse.run();
    cat.sleep();
}
else {
    console.log("ERROR cat or mouse  NULL");
}
},{}]},{},[1]);

compilation of ts in js with browserify

var browserify = require('browserify');
var tsify = require('tsify');

browserify()
    .add('src/test/typescript/animal.ts')
    .plugin(tsify, { noImplicitAny: true })
    .bundle()
    .on('error', function (error) { console.error(error.toString()); })
    .pipe(process.stdout);

build command of ts in js

node animal.build.js >  src/test/typescript/animal.js

animal.html This file is an example of use of animal.js that contains Animal class. The animal.js is loaded, but can't find Animal class from the html context!

   <!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8"> 
  <title>Animal test</title>
</head>
<body>
  <script type='text/javascript' src='https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js'></script>
  <script src="animal.js"></script>
  <script>

     $(document).ready(function() {
        console.log("html ready");
        console.log("now trying animal");

        var a = new Animal('titi');
            if(a === undefined || a ===null){
                console.log("ERROR a not defined!");
            }
            else{
                a.run();
            }
     });  




  </script>

</body>
</html>

Google Chrome console output of animal.html

Navigated to

file:///C:/dev/git/wscommerce/src/test/typescript/animal/animal.html
animal.js:8 Alfred:Animal runs.
animal.js:14 Gustavo:Animal sleeps.
animal.html:13 html ready
animal.html:14 now trying animal
animal.html:16 Uncaught ReferenceError: Animal is not defined(anonymous function) @ animal.html:16i @ jquery.min.js:2j.fireWith @ jquery.min.js:2n.extend.ready @ jquery.min.js:2J @ jquery.min.js:2

Problem You can see in the chrome console output that from within the typescript generated js, I can use the Animal class. But from animal.html, I can't find the reference. I encounter a scope / build problem on typescript.My target environnement webserver will be tomcat. I will package this scripts into a plain war. I do not want to deploy a nodejs server.

5
  • that's because you are probably compiling the typescript code to match some module loader, so you need a module loader to load your code. Commented Apr 10, 2016 at 14:33
  • also, asking the same question again will not guarantee you an answer. :) Commented Apr 10, 2016 at 14:36
  • how can i perform that can you give me a module loader that is lightweight and does not need to install node server on target environnement (will run in a simple tomcat server) Commented Apr 10, 2016 at 14:36
  • If loading a class from js is what you are looking after I answered a similar question here. stackoverflow.com/questions/36313093/… Commented Apr 10, 2016 at 14:38
  • it might be the same root problem, I'm trying to get helped and simplified my question. Commented Apr 10, 2016 at 14:38

3 Answers 3

1

Animal class is declared inside anonymous function and is also declared as a module, then external code will not see the Animal class. If you want to use Animal class you need to require Animal class:

var Animal = require('Animal');
var newAnimal = new Animal('test');
Sign up to request clarification or add additional context in comments.

3 Comments

will try that one now, using requirejs
requirejs is part of node delivery. This workaround adds a dependency in my project.
for that, I will not accept as solution this workaroud. I don't want to add dependencies to my project. The less dependencies I have, the better I live. :)
1

The solution that does not requieres dependencies, is :

1. add modules in all file

module Rizze{ // ts code ....
}

2. removing require clauses in ts files This will imply using Module.Class.function in order to use a references module.

3.1 build resources : gulpfile

 //gulp 

var gulp = require('gulp');

// for ts compil
var ts = require('gulp-typescript');


// For minification and offuscation
var rename = require('gulp-rename');
var stripDebug = require('gulp-strip-debug');
var uglify = require('gulp-uglify');

//css minification
var minifyCss = require('gulp-minify-css');
var concat = require('gulp-concat');

var paths = {
    js: 'src/main/**/*.ts',
    css: 'src/main/**/*.css',
    alljs: 'dist/js/all.js',
}
var tsProject = ts.createProject('tsconfig.json', { sortOutput: true });

gulp.task('default',  function() {
    return tsProject.src()
        .pipe(ts(tsProject))
        .pipe(gulp.dest('dist/js'));
});

3.2 build ressource: tsconfig.json

{
    "compilerOptions": {
        "target":  "ES5",
        "sourceMap": true,
        "removeComments": false,
        "charset":"UTF-8",      
        "noImplicitAny" : true  ,
        "outFile": "all.js"
    }
    ,

     "filesGlob": [     
        "src/main/typescript/*.ts",
        "!src/main/typescript/lib/**/*.ts"
    ]

}

With this config, it works without node, and without requirejs in a plain html/js environnement.

Comments

0

Just to be sure, in the chrome console be sure the animal.js is loading and it's loading fast enough to be called from your html code.

2 Comments

The order of the logs suggests the animal.js file gets interpreted before the 2nd <script> statement. The problem is with the generated code. :)
yes I've modified the html in order to take this advice in consideration. @toskv is right!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.