TypeScript学习笔记(二)之Browserify Gulp

来源:互联网 发布:一键越狱软件 编辑:程序博客网 时间:2024/06/01 01:33

1、使用Browserify将工程移入浏览器环境

1)安装Browserify,tsify(Browserify的插件,能够访问TypeScript编译器),vinyl-source-stream(将Browserify的输出文件适配成gulp能够解析的格式)

npm install --save-dev browserify tsify vinyl-source-stream

2)在src目录中新建一个index.html文件

<!DOCTYPE html><html> <head>  <meta charset="UTF-8" />  <title>Hello World!</title> </head> <body>  <p id="greeting">Loading ...</p> <script src="bundle.js"></script></body></html>

3)修改main.ts文件

import {sayHello} from "./greet";function showHello(divName: string, name: string){const elt = document.getElementById(divName);elt.innerText = sayHello(name);}showHello("greeting", "TypeScript");
4)修改gulpfile

var gulp = require("gulp");var browserify = require("browserify");var source = require('vinyl-source-stream');var tsify = require("tsify");var paths = {pages: ['src/*.html']};//增加copy-html并将它作为default的依赖项,当default执行时,copy-html会被首先执行gulp.task("copy-html", function() {return gulp.src(paths.pages).pipe(gulp.dest("dist"));});gulp.task("default", ["copy-html"], function() {return browserify({basedir: '.',debug: true,entries: ['src/main.ts'],cache: {},packageCache: {}})//使用tsify插件调用Browserify.plugin(tsify).bundle()//调用bundle后,使用source把输出文件命名为bundle.js.pipe(source('bundle.js')).pipe(gulp.dest("dist"));});

运行gulp,打开dist.index.html即可。

2、Watchify:启动Gulp并保持运行状态,保存文件时自动编译

Babel:编译器,将ES6以上版本转化为低版本

Uglify压缩代码

npm install --save-dev watchify gulp-util
修改gulpfile.js
var gulp = require("gulp");var browserify = require("browserify");var source = require('vinyl-source-stream');var watchify = require("watchify");var tsify = require("tsify");var gutil = require("gulp-util");var paths = {pages: ['src/*.html']};var watchedBrowserify = watchify(browserify({basedir: '.',debug: true,entries: ['src/main.ts'],cache: {},packageCache: {}}).plugin(tsify));//增加copy-html并将它作为default的依赖项,当default执行时,copy-html会被首先执行gulp.task("copy-html", function() {return gulp.src(paths.pages).pipe(gulp.dest("dist"));});function bundle() {return watchedBrowserify.bundle().pipe(source('bundle.js')).pipe(gulp.dest("dist"));}gulp.task("default", ["copy-html"], bundle);watchedBrowserify.on("update", bundle);watchedBrowserify.on("log", gutil.log);/*gulp.task("default", ["copy-html"], function() {return browserify({basedir: '.',debug: true,entries: ['src/main.ts'],cache: {},packageCache: {}})//使用tsify插件调用Browserify.plugin(tsify).bundle()//调用bundle后,使用source把输出文件命名为bundle.js.pipe(source('bundle.js')).pipe(gulp.dest("dist"));});*/



原创粉丝点击