如何使用Typescript + Uglify + Browserify

时间:2016-06-08 13:20:51

标签: typescript browserify visual-studio-code uglifyjs

我按照指南here进行了一些修改,以构建我的工作流程,以编译要在浏览器上使用的JavaScript库。但是当我尝试在firefox上测试已编译的js文件时,我得到了致命的TypeError: MyApp.Engine is not a constructor

我花了最近两天修复此问题并进行了许多谷歌搜索,但没有帮助...我在下面列出了所有必要的数据。  请告诉我如何使这项工作。

PS:我跑了"观看"关于gulp的任务,每个文件都按预期在正确的位置生成,但结果代码不起作用......

忍受我......

我的文件夹结构:

enter image description here

tsconfig.json

{
    "compilerOptions": {
        "target": "es5",
        "sourceMap": true,
        "module": "commonjs",
        "moduleResolution": "node",
        "isolatedModules": false,
        "jsx": "react",
        "experimentalDecorators": true,
        "emitDecoratorMetadata": true,
        "declaration": false,
        "noImplicitAny": false,
        "removeComments": true,
        "noLib": false,
        "preserveConstEnums": true,
        "suppressImplicitAnyIndexErrors": true
    }
}

gulpfile.js

var gulp = require("gulp"),
    browserify = require("browserify"),
    uglify = require('gulp-uglify'),
    tsc = require("gulp-typescript"),
    source = require("vinyl-source-stream"),
    buffer = require("vinyl-buffer"),
    runSequence = require('run-sequence'),
    sourcemaps = require("gulp-sourcemaps"),
    browserSync = require('browser-sync').create();

var tsProject = tsc.createProject("tsconfig.json");

gulp.task("build", function () {
    return gulp.src([
        "source/**/**.ts",
        "typings/main.d.ts/",
        "source/interfaces/interfaces.d.ts"
    ])
        .pipe(tsc(tsProject))
        .js.pipe(gulp.dest("build/"));
});

gulp.task("build-bundle", function (callback) {
    runSequence('build', 'bundle', callback);
});

gulp.task("bundle", function () {
    var libraryName = "MyApp";
    var mainTsFilePath = "build/engine.js";
    var outputFolder = "dist/";
    var outputFileName = libraryName + ".min.js";

    var bundler = browserify({
        debug: true,
        standalone: libraryName
    });

    return bundler.add(mainTsFilePath)
        .bundle()
        .pipe(source(outputFileName))
        .pipe(buffer())
        .pipe(sourcemaps.init({ loadMaps: true }))
        .pipe(uglify())
        .pipe(sourcemaps.write('./'))
        .pipe(gulp.dest(outputFolder));
});

gulp.task("watch", ["build-bundle"], function () {
    copyfunction();
    browserSync.init({
        server: "html"
    });

    gulp.watch(["source/**/**.ts", "test/**/*.ts"], ["build-bundle"]);
    gulp.watch("dist/*.js").on('change',copyfunction);
    gulp.watch("html/**/*").on('change', browserSync.reload);
});

function copyfunction() {
    gulp.src("dist/*.js")
    .pipe(gulp.dest("html/js"));
}

源/ Engine.ts

/// <reference path="SceneManager.ts" />
namespace MyLib {
    export class Engine {
        public sceneManager: MyLib.SceneManager;
        constructor(containerID:string)
        {
            this.sceneManager = new MyLib.SceneManager(containerID);
        }
    }
}

源/ SceneManager.ts

///<reference path="../typings/globals/three/index.d.ts" />
///<reference path="../typings/globals/three-orthographictrackballcontrols/index.d.ts" />

var container: HTMLElement;
var scene: THREE.Scene;
var HEIGHT: number;
var WIDTH: number;
var renderer: THREE.WebGLRenderer;
var camera: THREE.OrthographicCamera;
var controls: THREE.OrthographicTrackballControls;
var stats: Stats;
var shadowLight: any;

function handleWindowResize() {
    HEIGHT = window.innerHeight;
    WIDTH = window.innerWidth;

    camera.left = WIDTH / -2;
    camera.right = WIDTH / 2;
    camera.top = HEIGHT / 2;
    camera.bottom = HEIGHT / -2;

    renderer.setSize(WIDTH, HEIGHT);
    camera.updateProjectionMatrix();
    controls.handleResize();
    render();
}


function animate() {

    stats.begin();
    requestAnimationFrame(animate);
    controls.update();
    stats.end();
}

function render() {
    renderer.render(scene, camera);
}



namespace MyLib {
    export class SceneManager {
        constructor(containerID: string) {
            container = document.getElementById(containerID);
            this.init();
        }
        private init() {

            HEIGHT = window.innerHeight;
            WIDTH = window.innerWidth;

            this.createCamera();

            this.createScene();
            this.createLights();
            this.CreateOriginSphere();
            this.CreateXYPlane();
            this.createControls();
            render();
            animate();
        }



        private createControls() {
            controls = new THREE.OrthographicTrackballControls(camera, renderer.domElement);
            controls.rotateSpeed = 1.0;
            controls.zoomSpeed = 1.2;
            controls.panSpeed = 0.8;
            controls.noZoom = false;
            controls.noPan = false;
            controls.staticMoving = true;
            controls.dynamicDampingFactor = 0.3;
            controls.keys = [65, 83, 68];
            controls.addEventListener("change", render);


        }


        public createCamera() {
            camera = new THREE.OrthographicCamera(
                WIDTH / -2,
                WIDTH / 2,
                HEIGHT / 2,
                HEIGHT / -2,
                -100,
                300000
            );


            camera.position.x = -100;
            camera.position.y = -100;
            camera.position.z = 100;
            camera.up.set(0, 0, 1);
            camera.lookAt(new THREE.Vector3(0, 0, 0));
        }

        private createScene() {

            scene = new THREE.Scene();


            renderer = new THREE.WebGLRenderer({
                alpha: true,
                antialias: true
            });


            renderer.setSize(WIDTH, HEIGHT);
            renderer.shadowMap.enabled = true;


            container.appendChild(renderer.domElement);

            stats = new Stats();
            container.appendChild(stats.dom);

            window.addEventListener("resize", handleWindowResize, false);
        }





        private createLights() {
            shadowLight = new THREE.DirectionalLight(0xffffff, .9);
            shadowLight.position.set(150, 350, 350);
            shadowLight.castShadow = true;
            shadowLight.shadow.camera.left = -400;
            shadowLight.shadow.camera.right = 400;
            shadowLight.shadow.camera.top = 400;
            shadowLight.shadow.camera.bottom = -400;
            shadowLight.shadow.camera.near = 1;
            shadowLight.shadow.camera.far = 1000;
            shadowLight.shadow.mapSize.width = 2048;
            shadowLight.shadow.mapSize.height = 2048;
            scene.add(shadowLight);
        }

        private CreateOriginSphere() {
            var geometry = new THREE.SphereGeometry(5, 32, 32);
            var material = new THREE.MeshLambertMaterial({ color: 0x008080, overdraw: 0.5 });
            var mesh = new THREE.Mesh(geometry, material);
            mesh.position.x = 0;
            mesh.position.y = 0;
            mesh.position.z = 0;

            var object = new THREE.Object3D();
            object.name = "originsphere";
            object.userData = { originalColor: 0x008080 };

            object.add(mesh);
            scene.add(object);
        }

        private CreateXYPlane() {
            var a = 100;
            var material = new THREE.MeshPhongMaterial({ color: 0xd0afaf });
            var geometry = new THREE.Geometry();

            geometry.vertices.push(
                new THREE.Vector3(a, a, 0),
                new THREE.Vector3(-a, a, 0),
                new THREE.Vector3(-a, -a, 0),
                new THREE.Vector3(a, -a, 0)
            )

            geometry.faces.push(
                new THREE.Face3(0, 1, 3),
                new THREE.Face3(1, 2, 3)
            )

            geometry.computeBoundingSphere();
            geometry.computeFaceNormals();
            geometry.computeVertexNormals();

            var mesh = new THREE.Mesh(geometry, material);

            var object = new THREE.Object3D();
            object.name = "xyplane";
            object.userData = { originalColor: 0xd0afaf };
            object.add(mesh);
            scene.add(object);
        }
    }

}

dist / MyApp.min.js (似乎太短了?)

!function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var n;n="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,n.MyApp=e()}}(function(){return function e(n,r,o){function t(i,u){if(!r[i]){if(!n[i]){var d="function"==typeof require&&require;if(!u&&d)return d(i,!0);if(f)return f(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var c=r[i]={exports:{}};n[i][0].call(c.exports,function(e){var r=n[i][1][e];return t(r?r:e)},c,c.exports,e,n,r,o)}return r[i].exports}for(var f="function"==typeof require&&require,i=0;i<o.length;i++)t(o[i]);return t}({1:[function(e,n,r){var o;!function(e){var n=function(){function n(n){this.sceneManager=new e.SceneManager(n)}return n}();e.Engine=n}(o||(o={}))},{}]},{},[1])(1)});
//# sourceMappingURL=MyApp.min.js.map

HTML / index.html中

    ...
    <body>
    <script type="text/javascript" src="js/three.js"></script>
    <script type="text/javascript" src="js/controls/OrthographicTrackballControls.js"></script>
    <script type="text/javascript" src="js/libs/stats.min.js"></script>
    <script type="text/javascript" src="js/MyApp.min.js"></script>
    <script>

  var engine;
  window.onload = function() {
      engine= new MyApp.Engine("scenecontainer");
  }



         </script>

    <div id="scenecontainer"></div>
</body>
    ...

0 个答案:

没有答案