导入外部库并使用打字稿生成单个文件
Import external libraries and generate single file with typescript
在Gulp中,我使用Typescript将文件转译为ES6,然后使用Babel生成ES5,最后使用Browserify生成包含所有模块的1个文件。这是我的代码:
gulp.task('scripts', function() {
return browserify('./src/scripts/main.ts')
.plugin(tsify, {moduleResolution: "node", target:"es5", allowJs:true, allowUnreachableCode:true"})
.transform("babelify", {presets:["es2015"], extensions:[".ts", ".js"]})
.bundle()
//Pass desired output filename to vinyl-source-stream
.pipe(source('main.js'))
// Start piping stream to tasks!
.pipe(gulp.dest('./dist/scripts/'));
});
我认为,如果我只需要依赖 Typescript 来完成上述所有操作,那会更好并且更不容易出错。我用转译器试过这个
tsc --moduleResolution "node" --module "amd" --allowJs --outDir "out/" --allowUnreachableCode --out foo.js main.ts
这几乎可以正常工作,唯一的问题是它不会导入 jquery
或 d3
等外部库。也就是说,如果我的代码显示 import * as d3 from "d3"
,则不会导入任何内容。另一方面,Browserify 可以识别这些库并且可以毫不费力地导入它们。
我错过了什么?没有生成错误,所以我不知道发生了什么。
Browserify, on the other hand, recognizes these libraries and has no trouble importing them.
What am I missing?
请为外部库使用 browserify(或 webpack)。
基本上你有一个文件 d3.d.ts
是 实际 导入到上下文中而不是 node_modules/d3/*
。所以 TypeScript 不会为编译输出加载 node_modules/d3
。
更多
--allowJS
是为了方便 您此时的 JavaScript 迁移。您刚刚发现了可能存在的许多陷阱之一。
PS:如果 node_module 本身也在 TypeScript 中,TypeScript 很可能会正常工作。
在Gulp中,我使用Typescript将文件转译为ES6,然后使用Babel生成ES5,最后使用Browserify生成包含所有模块的1个文件。这是我的代码:
gulp.task('scripts', function() {
return browserify('./src/scripts/main.ts')
.plugin(tsify, {moduleResolution: "node", target:"es5", allowJs:true, allowUnreachableCode:true"})
.transform("babelify", {presets:["es2015"], extensions:[".ts", ".js"]})
.bundle()
//Pass desired output filename to vinyl-source-stream
.pipe(source('main.js'))
// Start piping stream to tasks!
.pipe(gulp.dest('./dist/scripts/'));
});
我认为,如果我只需要依赖 Typescript 来完成上述所有操作,那会更好并且更不容易出错。我用转译器试过这个
tsc --moduleResolution "node" --module "amd" --allowJs --outDir "out/" --allowUnreachableCode --out foo.js main.ts
这几乎可以正常工作,唯一的问题是它不会导入 jquery
或 d3
等外部库。也就是说,如果我的代码显示 import * as d3 from "d3"
,则不会导入任何内容。另一方面,Browserify 可以识别这些库并且可以毫不费力地导入它们。
我错过了什么?没有生成错误,所以我不知道发生了什么。
Browserify, on the other hand, recognizes these libraries and has no trouble importing them. What am I missing?
请为外部库使用 browserify(或 webpack)。
基本上你有一个文件 d3.d.ts
是 实际 导入到上下文中而不是 node_modules/d3/*
。所以 TypeScript 不会为编译输出加载 node_modules/d3
。
更多
--allowJS
是为了方便 您此时的 JavaScript 迁移。您刚刚发现了可能存在的许多陷阱之一。
PS:如果 node_module 本身也在 TypeScript 中,TypeScript 很可能会正常工作。