如何用gulp构建typescript开发环境
- 全局安装gulp
yarn global add gulp-cli 或 npm i gulp-cli -g
- 创建项目目录,如proj, 进入入proj目录,初始化项目, 并生成package.json文件。
yarn init-y 或 npm init -y
- 在项目目录创建src(源文件目录),output(编译打包输出)目录,并在src目录下创建index.html, main.ts文件,如less创建index.less文件,或直接index.css, 或index.sass
- output
- ts // .ts编译成js输出的目录
- src
- index.html
- main.ts
- index.less
- 安装依赖(开发依赖)
-
cross-env: 设置node环境。
-
gulp: gulp命令行工具,创建gulp任务并运行。
-
typscript: typsscript支持,将.ts文件编译成.js文件
-
gulp-typescript: typescript gulp插件,让gulp可以处理typescript文件。
-
browserify: 最终打包成一个bundle.js文件
-
watachify: 文件的监听,当要监听的文件发生修改时,会重新编译打包。
-
gulp-inject: 向模板注入.css或.js文件。
-
tsify: tsify是Browserify的一个插件,就像gulp-typescript一样,它能够访问TypeScript编译器。
-
vinyl-buffer: 读取一个vinyl对象流,并将流中的vinyl对象的内容(即contents属性,该工具主要是针对contents为Stream的对象,对于contents为Buffer类型的,则原样输出)全部读取并封装到一个Buffer中,返回一个相同的vinyl对象,但是将其contents换成封装好的Buffer。
-
vinyl-source-stream: 用于将一个Stream封装成一个vinyl对象,即创建一个vinyl对象,给它指定一个文件名,并将其contents设置为该Stream;需要注意的是,由于要封装的流本身只是一个流,并不是一个文件,所以这里指定的文件名是由用户随意指定的,可以说是假的文件名,但是这个假的文件名也可以被下游的输出流利用,例如使用该vinyl对象的文件名和路径将文件写到实际的文件系统中
-
gulp-sourcemaps: sourcemaps的gulp插件,生成转换后.js,.ts源码文件。
-
gulp-if: gulp进入判断
-
gulp-babel: babel的gulp插件, 是一个工具链,主要用于在旧的浏览器或环境中将 ECMAScript 2015+ 代码转换为向后兼容版本的 JavaScript 代码。
-
gulp-autoprefixer:autoprefixer的gulp插件,自动补齐css的各浏览器的前缀。
-
gulp-less: less的gulp插件,将less转换成css。
-
- 初始化ts项目配置文件tsconfig.json,并做相应的配置
tsc init
{
"files": [
"src/main.ts"
],
"compilerOptions": {
/* Visit https://aka.ms/tsconfig.json to read more about this file */
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es2015", /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019', 'ES2020', or 'ESNEXT'. */
"module": "commonjs", /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
// "outDir": "./", /* Redirect output structure to the directory. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true, /* Enable all strict type-checking options. */
"noImplicitAny": true, /* Raise error on expressions and declarations with an implied 'any' type. */
// "strictNullChecks": true, /* Enable strict null checks. */
// "strictFunctionTypes": true, /* Enable strict checking of function types. */
// "strictBindCallApply": true, /* Enable strict 'bind', 'call', and 'apply' methods on functions. */
// "strictPropertyInitialization": true, /* Enable strict checking of property initialization in classes. */
// "noImplicitThis": true, /* Raise error on 'this' expressions with an implied 'any' type. */
// "alwaysStrict": true, /* Parse in strict mode and emit "use strict" for each source file. */
/* Additional Checks */
// "noUnusedLocals": true, /* Report errors on unused locals. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
// "moduleResolution": "node", /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true, /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
/* Advanced Options */
"skipLibCheck": true, /* Skip type checking of declaration files. */
"forceConsistentCasingInFileNames": true /* Disallow inconsistently-cased references to the same file. */
}
}
- index.html文件内容如下,注入.css与.js文件时需要写上要注入的位置:
<!DOCTYPE >
<html>
<head>
<title>index</title>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome = 1" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" />
<!-- inject:css -->
<!-- endinject -->
</head>
<body>
<div id="app"></div>
<p id="greeting">Loading...</p>
<!-- inject:js -->
<!-- endinject -->
</body>
</html>
- src/main.ts, src/greets.ts文件内容如下:
// src/main.ts
import { sayHello } from './greet';
function showHello(domName: string, name: string) {
const elt = document.getElementById(domName) as HTMLElement;
elt.innerText = sayHello(name);
}
showHello('greeting', 'TypeScript');
// src/greet.ts
export function sayHello(name: string) {
return `Hello from ${name}`;
}
- index.less写上相应的样式即可
gulpfile.js文件的编写,这个是重点
const fs = require('fs'),
path = require('path'),
browserify = require('browserify'),
watchify = require('watchify'),
gulp = require('gulp'),
inject = require('gulp-inject'),
source = require('vinyl-source-stream'),
buffer = require('vinyl-buffer'),
gif = require('gulp-if'),
uglify = require('gulp-uglify'),
sourcemaps = require('gulp-sourcemaps'),
babel = require('gulp-babel'),
autoprefixer = require('gulp-autoprefixer'),
less = require('gulp-less');
const ts = require('gulp-typescript'),
tsProject = ts.createProject('tsconfig.json'),
tsify = require('tsify');
const isProduction = /production/.test(process.env.NODE_ENV);
// 处理.js文件
function bundleJs( ) {
const b = browserify({
entries: ['./src/index.js'],
cache: {},
packageCache: {},
plugin: [watchify]
});
b.on('update', bundle);
bundle();
function bundle() {
b.bundle().on('error', console.error)
.pipe(source('bundle.js'))
.pipe(buffer())
.pipe(sourcemaps.init())
.pipe(babel({presets: ['@babel/env']}))
.pipe(sourcemaps.write('.'))
.pipe(gif(isProduction, uglify()))
.pipe(gulp.dest('./output/'));
// .pipe(fs.createWriteStream('./output/bundle.js'));
}
}
function injectFun() {
const target = gulp.src('./src/index.html');
const sources = gulp.src(['./output/**/*.js', './output/**/*.css'], { read: false}, {relative: true});
target.pipe(inject(sources))
.pipe(gulp.dest('./output'));
}
function lessTask() {
gulp.src('./src/**/*.less')
.pipe(gif(!isProduction, sourcemaps.init()))
.pipe(less({paths: [path.join(__dirname, 'less', 'includes')]}))
.pipe(autoprefixer())
.pipe(gif(!isProduction, sourcemaps.write()))
.pipe(gulp.dest('./output'))
}
function defaultTask( cb ) {
bundleJs();
handleTs();
cb();
}
function handleTs() {
const b = browserify({
entries: ['./src/main.ts'],
cache: {},
packageCache: {},
plugin: [watchify, tsify]
})
b.on('update', bundle);
bundle();
function bundle() {
b.bundle().on('error', console.error)
.pipe(source('bundleTs.js'))
.pipe(buffer())
.pipe(sourcemaps.init())
.pipe(babel({presets: ['@babel/env']}))
.pipe(sourcemaps.write('.'))
.pipe(gif(isProduction, uglify()))
.pipe(gulp.dest('./output/ts'))
}
}
exports.default = gulp.parallel(gulp.series(defaultTask, injectFun), lessTask);
- 在package.json"script"标签中写上脚本
"scripts": {
"start": "cross-env NODE_ENV=development gulp",
"build": "cross-env NODE_ENV=production gulp"
},
最后在命令行输入yarn start,运行完gulp task,并相对相应的文件做监听,在浏览器中打开index.hmtl文件即可。