I created a Gui library that works fine when i test it from within the project. Now i want to use it as a library, for my sound generation application.
Seems simple, but i couldn't get anything despite many changes in my references or compiler options...
I use 1.6.2 version of typescript, target es5, use commonjs formodule in both tsconfig.json files . moduleResolution is classic.
I don't know if that matters, but i use experimentalDecorators and i output declaration file and inlined source map.
What i have so far is like (simplified version):
••• Library files •••
shapes.ts
shapes/rect.ts
shapes/roundrect.ts
shapes.ts is the main module. Since i've read that files are already modules, i did not use the modulekeyword.
// shapes.ts
/// <reference path="./shapes/rect.ts"/>
/// <reference path="./shapes/roundrect.ts"/>
export * from "./shapes/rect.ts";
export * from "./shapes/roundrect.ts"
--
// rect.ts
export class Rect {
x : number;
y : number;
...
}
--
// roundrect.ts
/// <reference path="./rect.ts"/>
import {Rect} from "./rect.ts";
export class RoundRect extends Rect {
cornerRadius : number;
...
}
••• App files •••
for the App file, i made many attemps, i would like to be able to write :
var MyRect = new Rect();
or :
var MyRect = new Shapes.Rect();
So i tried a lot of import syntax, since no two blogs or docs says the same about this syntax :
import * as Shapes from '../../shapes/dst/shapes';
Or
import Shapes = require('../../shapes/dst/shapes');
Or
import {Rect, RoundRect} from '../../shapes/dst/shapes';
Or
var Shapes = require('../../shapes/dst/shapes');
( Or all above examples from the src and not the dst folder) .
All those examples get marked as a wrong path in the editor.
I also tried all examples above with or without :
/// <reference path="../../shapes/rect.ts"/>
Rq the path is marked correct with reference, but when using a reference path, there are a lot of 'Cannot find module' errors.
So bottom line, i always get, for the module import, the same error :
Cannot find module '../../shapes/dst/shapes'
¿¿¿ How can i use my lib ???
If you have multiple classes exported inside a file, it makes sense to use a module.
If you'd rather export a class as a module itself, you can try export =
Example:
class RoundRect {
....
}
export = RoundRect;
http://www.typescriptlang.org/Handbook#modules-export-
Related
Currently in Web-Essentials (for Visual Studio 2015), if a .ts file from the Solution Explorer is dragged and dropped into an open .ts file, a reference path is automatically inserted at the top:
/// <reference path="../playback/key.ts" />
This is fine when a project is being developed using internal modules (namespaces), but is virtually useless when going external. How could I make it so that an ES6 import statement is generated instead? That would be awesome. Such as:
import {} from "../playback/key";
It turns out what we are seeing is a built-in feature of Web-Essentials. I've filed a feature-request to get this available, hopefully in the near future.
In the meantime, the following Visual Commander automation snippet can replace all references to ES6 imports:
using EnvDTE;
using EnvDTE80;
using System.Text.RegularExpressions;
public class C : VisualCommanderExt.ICommand
{
// Called by Visual Commander extension.
public void Run(EnvDTE80.DTE2 DTE, Microsoft.VisualStudio.Shell.Package package)
{
TextDocument doc = (TextDocument)(DTE.ActiveDocument.Object("TextDocument"));
var p = doc.StartPoint.CreateEditPoint();
string s = p.GetText(doc.EndPoint);
p.ReplaceText(doc.EndPoint, this.ReplaceReferences(s), (int)vsEPReplaceTextOptions.vsEPReplaceTextKeepMarkers);
}
// Converts "reference" syntax to "ES6 import" syntax.
private string ReplaceReferences(string text)
{
string pattern = "\\/\\/\\/ *<reference *path *= *\"([^\"]*)(?:\\.ts)\" *\\/>";
var regex = new Regex(pattern);
var matches = Regex.Matches(text, pattern);
return Regex.Replace(text, pattern, "import {} from \"./$1\";");
}
}
The regex used to perform this replace is (without the double backslashes, more readable):
\/\/\/ *<reference *path *= *"([^"]*)(?:\.ts)" *\/>
This snippet will effectively convert all reference comments to ES6 imports in the currently active document, very useful.
Known issues:
a comment containing a reference tag is not recognized by Visual Studio if it is preceded by other text in the corresponding line, but it is still replaced by this snippet
additional text after a reference tag is valid, but after replace will cause syntax errors, since it is no longer a comment.
(Neither of these issues are relevant if the snippet is used on reference tags generated by Web-Essentials when a .ts file is drag-and-dropped.)
I'm stuck with the right way to import an AMD JavaScript library (https://github.com/dcodeIO/bytebuffer.js) into a TypeScript file.
I found its - not up-to-date - type definition (https://github.com/SINTEF-9012/Proto2TypeScript/commit/0889dccbf6048f116551a73e77d75dd83553cfe6), but actually I was not able to find a way to use it and have the library loaded by RequireJS.
This is the code I'm using:
/// <amd-dependency path="Scripts/bytebuffer" />
var ByteBuffer = require( 'Scripts/bytebuffer' );
import protocols = require( 'protocols' );
export class Pippo
{
readPayload( payload: ArrayBuffer, ECType: string ): any
{
var ECStruct = new protocols.ECStruct( ECType );
var bb = new ByteBuffer()
.writeIString( "Hello world!" )
.flip();
console.log( bb.readIString() + " from bytebuffer.js" );
}
}
The two modules protocols and bytebuffer are loaded correctly, but actually I cannot see members of instance bb in Visual Studio. If I put the line
/// <reference path="scripts/typings/bytebuffer/bytebuffer.d.ts" />
and comment
//var ByteBuffer = require( 'Scripts/bytebuffer' );
of course I can see methods and properties of bb, but the module is not loaded at runtime.
Is there a way to have the ByteBuffer.js loaded by RequireJS with the possibility to see its members in VS?
Thanks
There is a syntax for declaring the interface of external modules:
declare module 'amd/module/name' {
// module definition, probably with:
exports = thingToExport;
}
In your case it should probably be:
declare module 'Scripts/bytebuffer' {
exports = ByteBuffer;
}
Put this after the bytebuffer.d.ts file!!! Also see "Writing .d.ts files" in the handbook.
In my case the /// <amd-dependency> and /// <reference> stuff were also redundant - you may want to try it too, to simplify your code.
I'm using TypeScript and require.js to resolve dependencies in my files. I'm in a situation where I want to reference a static field of a class in an other file, but in the same internal module (same folder) and I am not able to access it, even if the Visual Studio pre-compiler does not show any error in my code.
I have the following situation :
Game.ts
class Game {
// ...
static width: number = 1920;
// ...
}
export = Game;
Launcher.ts
/// <reference path='lib/require.d.ts'/>
import Game = require("Game");
var width: number = Game.width;
console.log(width); // Hoping to see "1920"
And the TypeScript compiler is ok with all of this. However, I keep getting "undefined" at execution when running the compiled Launcher.ts.
It's the only reference problem I'm having in my project, so I guess the rest is configured correctly.
I hope I provided all necessary information, if you need more, please ask
Any help is appreciated, thanks !
Your code seems sound, so check the following...
You are referencing require.js in a script tag on your page, pointing at Launcher (assuming Launcher.ts is in the root directory - adjust as needed:
<script src="Scripts/require.js" data-main="Launcher"></script>
Remove the reference comment from Launcher.ts:
import Game = require("Game");
var width: number = Game.width;
console.log(width); // Hoping to see "1920"
Check that you are compiling using --module amd to ensure it generates the correct module-loading code (your JavaScript output will look like this...)
define(["require", "exports", "Game"], function (require, exports, Game) {
var width = Game.width;
console.log(width); // Hoping to see "1920"
});
If you are using Visual Studio, you can set this in Project > Properties > TypeScript Build > Module Kind (AMD)
If you are using require.js to load the (external) modules, the Game class must be exported:
export class Game {}
If you import Game in Launcher.ts like
import MyGame = require('Game')
the class can be referenced with MyGame.Game and the static variable with MyGame.Game.width
You should compile the ts files with tsc using option --module amd or the equivalent option in Visual Studio
I'm developing an NPM package using typescript. Within this package the TS files are setup as external modules. The compiler won't generate a single .d.ts for external modules. I'm trying to concat all tsc generated type definitions into a single .d.ts for the entire package.
I'm having issues laying out the single .d.ts file (following a similar approach to that used in grunt-dts-bundle). The condensed example below captures my issue.
Given this external module declaration and test file:
test.d.ts :
declare module "ExternalWrapper" {
export import Foo = require("FooModule");
}
declare module "FooModule" {
class Foo {
name: string;
}
export = Foo;
}
test.ts:
import externalWrapper = require( 'ExternalWrapper' );
var t = new externalWrapper.Foo();
Running tsc test.ts test.d.ts -m commonjs produces this error: TS2083: Invalid 'new' expression.
If you change 'test.ts' to look like this, importing 'FooModule' directly:
import Foo = require( "FooModule" );
var t = new Foo();
It compiles fine.
The compiler understands the type externalWrapper.Foo however it doesn't seem to represent it as the same type FooModule.Foo. There is something I'm not getting about how the compilers handles modules that are exported via 'export import'.
Failing the above I'll probably look to manually creating the .d.ts :(
Any help appreciated.
You are probably missing a reference tag:
/// <reference path="test.d.ts"/>
It works :
You should be able to fix this by modifying your .d.ts file to resemble the following:
declare module "ExternalWrapper" {
import FooModule = require("FooModule");
export var Foo: typeof FooModule;
}
declare module "FooModule" {
class Foo {
name: string;
}
export = Foo;
}
With the export import syntax the compiler was assuming you were exporting an instance of Foo, not Foo itself... a little quirky.
Simple question.
Does AMD DOJO implementation support these type of declarations?
text!./plain.html
define(["../Widget","text!./plain.html"],
function(Widget,plain){
return new Widget({name:"mainApp",template:plain});
});
Load non-modules, let's say underscore.js
require(['dir/underscore.js'], function(){
_.reduce ...
});
Yes, but the precise syntax is different to that used in the question.
The Dojo Loader (1.7)
Plugins
dojo/text
The plugin for loading character data is dojo/text.
The extension should not be used when loading a JavaScript library and the location of the file is set via either a relative of the dojotoolkit base or a packages location declaration in dojoConfig:
require(['underscore'], function( _ ){
_.reduce ...
});
Configure the namespace in the Dojo configuration to avoid messy import paths - see dojoConfig in the loader documentation.
Also, consider using the dojo/global module and/or defining a Dojo module as a wrapper for Underscore.js:
//_.js
define(['dojo/global', 'underscore'], function(global){
return global._
});
With the above consideration, you must have loaded the actual .js file manually. If in conjunction with the dojo/text plugin, one would create a wrapper which also loads the required JS and evaluates it, following could do the trick.
/var/www/dojo-release-1.7/ext_lib/_.js - this sample file is hierachially placed in a library namespace, alongside dojo, dijit, dojox
define(['dojo/global', 'dojo/text!./Underscore.js'], function(global, scriptContents){
global.eval(scriptContents);
return global._ // '_' is the evaluated reference from window['_']
/**
* Alternatively, wrap even further to maintain a closure scope thus hiding _ from global
* - so adapt global.eval to simply eval
* - remove above return statement
* - return a dojo declared module with a getInstance simple method
*/
function get_ () { return _ };
var __Underscore = declare('ext_lib._', [/*mixins - none*/], {
getInstance: get_
});
// practical 'static' reference too, callable by 'ext_lib.getInstance' without creating a 'new ext_lib._'
__Underscore.getInstance = get_;
return __Underscore;
});
A sample of defining own modules using declare here
Note: this code is untested; feel free to add corrections.