Created
January 19, 2015 20:58
-
-
Save jbrantly/7a374d27f329a651fbec to your computer and use it in GitHub Desktop.
Prototype of typescript webpack loader
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
var typescript = require('typescript') | |
var path = require('path') | |
var compilerOptions = { | |
target: typescript.ScriptTarget.ES5 | |
} | |
var files = {}; | |
var servicesHost = { | |
getScriptFileNames: function () { return Object.keys(files) }, | |
getScriptVersion: function (filename) { return files[filename] && files[filename].version.toString() }, | |
getScriptSnapshot: function (filename) { | |
var file = files[filename]; | |
return { | |
getText: function (start, end) { return file.text.substring(start, end) }, | |
getLength: function () { return file.text.length }, | |
getLineStartPositions: function () { return [] }, | |
getChangeRange: function (oldSnapshot) { return undefined } | |
}; | |
}, | |
getCurrentDirectory: function () { return process.cwd() }, | |
getScriptIsOpen: function () { return true }, | |
getCompilationSettings: function () { return compilerOptions }, | |
getDefaultLibFilename: function (options) { return 'lib.d.ts' }, | |
log: function (message) { console.log(message) } | |
}; | |
var langService = typescript.createLanguageService(servicesHost, typescript.createDocumentRegistry()) | |
module.exports = function (content) { | |
var filePath = path.normalize(this.resourcePath); | |
if (!Object.prototype.hasOwnProperty.call(files, filePath)) { | |
var program = typescript.createProgram([filePath], compilerOptions, typescript.createCompilerHost(compilerOptions)); | |
program.getSourceFiles().forEach(function (file) { | |
files[path.normalize(file.filename)] = { version: 0, text: file.text }; | |
}) | |
} | |
var file = files[filePath]; | |
file.text = content; | |
file.version++; | |
var output = langService.getEmitOutput(filePath); | |
var diagnostics = langService.getCompilerOptionsDiagnostics() | |
.concat(langService.getSyntacticDiagnostics(filePath)) | |
.concat(langService.getSemanticDiagnostics(filePath)); | |
diagnostics.forEach(function(diagnostic) { | |
var lineChar = diagnostic.file.getLineAndCharacterFromPosition(diagnostic.start); | |
this.emitError(' ' +diagnostic.file && diagnostic.file.filename + ' (' + lineChar.line + ', ' + lineChar.character + '): ' + diagnostic.messageText) | |
}.bind(this)); | |
if (output.outputFiles.length == 0) return ''; | |
return output.outputFiles[0].text; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment