Skip to content

Commit

Permalink
Initial commit
Browse files Browse the repository at this point in the history
  • Loading branch information
denvned committed Sep 12, 2015
0 parents commit 2f99f9f
Show file tree
Hide file tree
Showing 18 changed files with 2,726 additions and 0 deletions.
7 changes: 7 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
lib
node_modules
*.sublime-project
*.sublime-workspace
.vscode
.idea
*.iml
8 changes: 8 additions & 0 deletions .npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
src
typings
tsconfig.json
*.sublime-project
*.sublime-workspace
.vscode
.idea
*.iml
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
The MIT License (MIT)

Copyright (c) 2015 Denis Nedelyaev

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
51 changes: 51 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
TypeScript Loader for *webpack*
===============================

*webpack-typescript* is a lightweight TypeScript loader for *webpack* allowing you to pack multiple modules written in TypeScript into a bundle. It supports not only TypeScript 1.5, but also TypeScript 1.6, which among other things introduces support for React JSX.

Installation
------------

To install *webpack-typescript* run the following command in your project directory:

npm install webpack-typescript --save-dev

And if you need TypeScript 1.6 Beta, run the following command before or after installing *webpack-typescript:*

npm install typescript@1.6.0-beta --save-dev

Configuration
-------------

Here is a sample *webpack.config.js* file featuring *webpack-typescript* loader:

```javascript
module.exports = {
entry: './index',
output: {
path: __dirname + '/dist',
filename: 'bundle.js'
},
resolve: {
extensions: ['', '.js', '.ts', '.tsx']
},
module: {
loaders: [
{
test: /\.tsx?$/,
loader: 'webpack-typescript'
}
]
}
}
```

[Here](http://webpack.github.io/docs/configuration.html) you can find more about configuring *webpack*.

### Compiler Options

TypeScript compiler options can be supplied by the standard [tsconfig.json](https://github.com/Microsoft/TypeScript/wiki/tsconfig.json) file. Note that the `"files"` and `"exclude"` sections are ignored, because now *webpack* decides what to compile.

*webpack-typescript* uses the same algorithm to find *tsconfig.json* as TypeScript compiler uses itself, i.e. first look in the current working directory, then in ancestor directories until it is found.

**Important note:** When using *webpack-typescript*, it is most logical to set `"target"` to `"ES5"`, and `"module"` to `"commonjs"`, but it should be also possible to target ES6 and pipe output to [babel-loader](https://github.com/babel/babel-loader), for example.
31 changes: 31 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
{
"name": "webpack-typescript",
"version": "0.5.1",
"author": "Denis Nedelyaev",
"license": "MIT",
"description": "Lightweight TypeScript Loader for webpack.",
"keywords": [
"typescript-loader",
"ts-loader",
"webpack-loader",
"typescript",
"loader",
"webpack",
"ts",
"tsx",
"jsx"
],
"homepage": "https://github.com/denvned/webpack-typescript",
"bugs": "https://github.com/denvned/webpack-typescript/issues",
"repository": {
"type": "git",
"url": "https://github.com/denvned/webpack-typescript.git"
},
"main": "lib/index.js",
"peerDependencies": {
"typescript": "^1.5.3 || ^1.6.0-beta"
},
"devDependencies": {
"typescript": "^1.6.0-beta"
}
}
28 changes: 28 additions & 0 deletions src/CompilationRequest.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
/// <reference path="../typings/node/node.d.ts" />

import * as ts from 'typescript';
import * as path from 'path';
import * as os from 'os';

export default class CompilationRequest {
inputFileName: string;
options: ts.CompilerOptions;
newLine: string;

constructor(inputFileName: string, public input: string, options: ts.CompilerOptions) {
this.inputFileName = path.normalize(inputFileName);
this.options = options;

if (options.newLine === ts.NewLineKind.CarriageReturnLineFeed) {
this.newLine = '\r\n';
} else if (options.newLine === ts.NewLineKind.LineFeed) {
this.newLine = '\n'
} else {
this.newLine = os.EOL;
}
}

isInputFile(fileName: string) {
return path.normalize(fileName) === this.inputFileName;
}
}
5 changes: 5 additions & 0 deletions src/CompilationResult.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
export default class CompilationResult {
inputFiles: string[];
output: string;
sourceMap: any;
}
27 changes: 27 additions & 0 deletions src/Diagnostics.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import * as ts from 'typescript';

export default class Diagnostics {
private diagnostics: ts.Diagnostic[] = [];

get isEmpty() {
return this.diagnostics.length === 0;
}

add(diagnostics: ts.Diagnostic[]) {
this.diagnostics = this.diagnostics.concat(diagnostics);
}

toString() {
let text = '';

this.diagnostics.forEach(diagnostic => {
if (diagnostic.file) {
const loc = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start);
text += `${diagnostic.file.fileName}(${loc.line + 1},${loc.character + 1}): `;
}
const category = ts.DiagnosticCategory[diagnostic.category].toLowerCase();
text += `${category} TS${diagnostic.code}: ${ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n')}\n`;
});
return text;
}
}
100 changes: 100 additions & 0 deletions src/LanguageServiceHost.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
/// <reference path="../typings/node/node.d.ts" />

import * as ts from 'typescript';
import * as path from 'path';
import * as fs from 'fs';
import CompilationRequest from './CompilationRequest';
import cwd from './cwd'
import {tracedMethod} from './util/traced';
import trace from './util/trace';

export default class LanguageServiceHost implements ts.LanguageServiceHost {
private projectVersion: number = 0;
private request: CompilationRequest;

@tracedMethod()
setCompilationRequest(request: CompilationRequest) {
if (!Object.isFrozen(request)) {
throw new TypeError('request should be frozen');
}
if (!Object.isFrozen(request.options)) {
throw new TypeError('request.options should be frozen');
}
this.request = request;
this.projectVersion++;
}

@tracedMethod()
getProjectVersion() {
return this.projectVersion.toString();
}

@tracedMethod()
getCompilationSettings() {
return this.request.options;
}

@tracedMethod()
getCurrentDirectory() {
return cwd;
}

@tracedMethod()
getScriptFileNames() {
return [path.relative(cwd, this.request.inputFileName)];
}

@tracedMethod({ return: false })
getScriptSnapshot(fileName: string) {
const filePath = path.resolve(cwd, fileName);
let source: string;
if (this.request.isInputFile(filePath)) {
trace('Using input');
source = this.request.input;
} else {
try {
trace('Reading file: ' + filePath);
source = fs.readFileSync(filePath, 'utf8');
} catch (err) {
trace('Failed to read file');
return void 0;
}
}
return ts.ScriptSnapshot.fromString(source);
}

@tracedMethod()
getScriptVersion(fileName: string) {
const filePath = path.resolve(cwd, fileName);
try {
return fs.statSync(filePath).mtime.toISOString();
} catch (err) {
return void 0;
}
}

@tracedMethod()
getDefaultLibFileName() {
return path.resolve(path.dirname(ts.sys.getExecutingFilePath()), ts.getDefaultLibFileName(this.request.options)); // HACK: ts understands absolute path only
}

@tracedMethod()
getNewLine() {
return this.request.newLine;
}

/* HACK: resolveSync of Webpack throws errors most of the time
@tracedMethod()
resolveModuleNames(moduleNames: string[], containingFile: string) {
const dir = path.dirname(containingFile);
return moduleNames.map(moduleName => {
try {
return this.request.resolveFn(dir, moduleName);
} catch (err) {
return void 0;
}
});
}
*/
}
83 changes: 83 additions & 0 deletions src/OptionsBuilder.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,83 @@
/// <reference path="../typings/node/node.d.ts" />

import * as ts from 'typescript';
import * as path from 'path'
import Diagnostics from './Diagnostics';

export default class OptionsBuilder {
private options: ts.CompilerOptions = {};

constructor(public diagnostics: Diagnostics) {}

addConfigFileText(filePath: string, content: string) {
const result = ts.parseConfigFileText(filePath, content);
if (result.error) {
this.diagnostics.add([result.error]);
} else {
this.addConfig(result.config, path.dirname(filePath));
}
return this;
}

addConfig(config: any, basePath: string) {
const options = parseOptions.call(this);

if (options) {
addOptions.call(this);
}
return this;

function parseOptions() {
config.files = [];
const result = ts.parseConfigFile(config, ts.sys, basePath);

if (result.errors.length > 0) {
this.diagnostics.add(result.errors);
return null;
} else {
return result.options;
}
}

function addOptions() {
for (const key in options) {
if (options.hasOwnProperty(key)) {
this.options[key] = options[key];
}
}
}
}

build(sourceMap: boolean) {
const options = this.options;
this.options = {};

adjustOptions();

return Object.freeze(options);

function adjustOptions() {
delete options.out;
delete options.outFile;
delete options.declaration;
delete options.emitBOM;

if (sourceMap) {
if (options.inlineSourceMap) {
delete options.inlineSourceMap;
options.sourceMap = true;
}
if (typeof options.sourceMap === 'undefined') {
options.sourceMap = true;
}
if (options.sourceMap) {
options.inlineSources = true;
}
} else {
delete options.sourceMap;
delete options.inlineSourceMap;
delete options.inlineSources;
}
}
}
}
Loading

0 comments on commit 2f99f9f

Please sign in to comment.