Created
February 14, 2017 04:28
-
-
Save xuecan/906c8f493a51a466e506b18b7f4f8192 to your computer and use it in GitHub Desktop.
TypeScript 的 import 语句要求模块名称是字符串字面量(不能是模板、变量等),这个 gulp 插件用于修改 import 语句中的模块名
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /*! | |
| Copyright (C) 2015-2017 Xue Can <xuecan@gmail.com> and contributors. | |
| Licensed under the MIT license: http://opensource.org/licenses/mit-license | |
| */ | |
| // TypeScript 的 import 语句要求模块名称是字符串字面量(不能是模板、变量等) | |
| // 有时候我们需要根据当前文件名做一些相对的导入(通常结合 requirejs 插件) | |
| // 这个 gulp 插件用于替换 import 语句中如下形式的字符串: | |
| // | |
| // - @@filename@@: 替换为文件名 | |
| // - @@basename@@: 替换为文件不含扩展名的部分 | |
| // - @@dirname@@: 替换为文件所在的路径 | |
| // | |
| // 局限性:只对 import 开始的行有效 | |
| var path = require("path"); | |
| var through = require("through2"); // npm install --save through2 | |
| var PluginError = require('gulp-util').PluginError; | |
| // consts | |
| var PLUGIN_NAME = 'gulp-modify-typescript-import'; | |
| module.exports = function() { | |
| return through.obj(function(file, encoding, callback) { | |
| var filename = path.basename(file.path); | |
| var basename = path.basename(file.path, ".ts"); | |
| var dirname = path.dirname(file.path); | |
| if (file.isNull()) { | |
| // nothing to do | |
| return callback(null, file); | |
| } | |
| if (file.isStream()) { | |
| // file.contents is a Stream - https://nodejs.org/api/stream.html | |
| this.emit('error', new PluginError(PLUGIN_NAME, 'Streams not supported!')); | |
| // or, if you can handle Streams: | |
| //file.contents = file.contents.pipe(... | |
| //return callback(null, file); | |
| } else if (file.isBuffer()) { | |
| var lines = String(file.contents).split("\n"); | |
| for (var i = 0; i < lines.length; i++) { | |
| var line = lines[i]; | |
| if (line.trim().search("import") === 0) { | |
| line = line.replace("@@filename@@", filename); | |
| line = line.replace("@@basename@@", basename); | |
| line = line.replace("@@dirname@@", dirname); | |
| lines[i] = line; | |
| } | |
| } | |
| file.contents = new Buffer(lines.join("\n")); | |
| return callback(null, file); | |
| } | |
| }); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment