Git Product home page Git Product logo

tslib's Introduction

tslib

This is a runtime library for TypeScript that contains all of the TypeScript helper functions.

This library is primarily used by the --importHelpers flag in TypeScript. When using --importHelpers, a module that uses helper functions like __extends and __assign in the following emitted file:

var __assign = (this && this.__assign) || Object.assign || function(t) {
    for (var s, i = 1, n = arguments.length; i < n; i++) {
        s = arguments[i];
        for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
            t[p] = s[p];
    }
    return t;
};
exports.x = {};
exports.y = __assign({}, exports.x);

will instead be emitted as something like the following:

var tslib_1 = require("tslib");
exports.x = {};
exports.y = tslib_1.__assign({}, exports.x);

Because this can avoid duplicate declarations of things like __extends, __assign, etc., this means delivering users smaller files on average, as well as less runtime overhead. For optimized bundles with TypeScript, you should absolutely consider using tslib and --importHelpers.

Installing

For the latest stable version, run:

npm

# TypeScript 3.9.2 or later
npm install tslib

# TypeScript 3.8.4 or earlier
npm install tslib@^1

# TypeScript 2.3.2 or earlier
npm install [email protected]

yarn

# TypeScript 3.9.2 or later
yarn add tslib

# TypeScript 3.8.4 or earlier
yarn add tslib@^1

# TypeScript 2.3.2 or earlier
yarn add [email protected]

bower

# TypeScript 3.9.2 or later
bower install tslib

# TypeScript 3.8.4 or earlier
bower install tslib@^1

# TypeScript 2.3.2 or earlier
bower install [email protected]

JSPM

# TypeScript 3.9.2 or later
jspm install tslib

# TypeScript 3.8.4 or earlier
jspm install tslib@^1

# TypeScript 2.3.2 or earlier
jspm install [email protected]

Usage

Set the importHelpers compiler option on the command line:

tsc --importHelpers file.ts

or in your tsconfig.json:

{
    "compilerOptions": {
        "importHelpers": true
    }
}

For bower and JSPM users

You will need to add a paths mapping for tslib, e.g. For Bower users:

{
    "compilerOptions": {
        "module": "amd",
        "importHelpers": true,
        "baseUrl": "./",
        "paths": {
            "tslib" : ["bower_components/tslib/tslib.d.ts"]
        }
    }
}

For JSPM users:

{
    "compilerOptions": {
        "module": "system",
        "importHelpers": true,
        "baseUrl": "./",
        "paths": {
            "tslib" : ["jspm_packages/npm/[email protected]/tslib.d.ts"]
        }
    }
}

Deployment

  • Choose your new version number
  • Set it in package.json and bower.json
  • Create a tag: git tag [version]
  • Push the tag: git push --tags
  • Create a release in GitHub
  • Run the publish to npm workflow

Done.

Contribute

There are many ways to contribute to TypeScript.

Documentation

tslib's People

Contributors

acutmore avatar alan-agius4 avatar aluanhaddad avatar andarist avatar andrewbranch avatar apendua avatar billti avatar danielrosenwasser avatar dependabot[bot] avatar diogoteles08 avatar exe-boss avatar frankwallis avatar iliyazelenko avatar jakebailey avatar lolipop99 avatar mgunter6 avatar mhegazy avatar microsoft-github-policy-service[bot] avatar nicholaslyang avatar orta avatar penx avatar rbuckton avatar ryancavanaugh avatar sandersn avatar saulzi avatar simenb avatar stevemoser avatar styfle avatar timbru31 avatar weswigham avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

tslib's Issues

Unable to build react project when using tslib

I wanted to try using tslib with my React project, but am running into tsc compiler errors. It works fine with Webpack, but when compiling with "tsc" the React type definitions are not playing nicely.

186     class PureComponent<P, S> extends Component<P, S> { }
                                  ~~~~~~~~~~~~~~~~~~~~~~~
node_modules/@types/react/index.d.ts(186,31): error TS2354: This syntax requires an imported helper but module 'tslib' cannot be found.

I have tslib installed as a dev-dependency and in my tsconfig.json I have the compilerOption set: "importHelpers": true

[email protected] breaks typeorm

After upgrading tslib to 1.12, I get the following error message when requiring 'typeorm'(which requiring tslib@^1.9.0)

> require('typeorm')
Uncaught:
TypeError: Cannot set property EntityManager of #<Object> which has only a getter
    at Object.<anonymous> (/path/to/typeorm-test/node_modules/typeorm/index.js:120:23)
    at Module._compile (internal/modules/cjs/loader.js:1158:30)
    at Object.Module._extensions..js (internal/modules/cjs/loader.js:1178:10)
    at Module.load (internal/modules/cjs/loader.js:1002:32)
    at Function.Module._load (internal/modules/cjs/loader.js:901:14)
    at Module.require (internal/modules/cjs/loader.js:1044:19)
    at require (internal/modules/cjs/helpers.js:77:18)

It seems like there's breaking changes in tslib.__exportStar() that defining getter instead of defining properties on target object. Resulting that once a symbol has already been exported by export * from './other-files' indirectly, the above error will be thrown when it is explicitly exported again in same file.

__spread Performance Issues

__spread

var tslib = require("tslib");
const { concat } = require('lodash')

var testPushES6 = function(abc) {
    var arr1 = [1,2,3,-1]
    var arr2 = [4,5,6,7,8,9,10,12,13,14,15,16,17,18,29,30,31,32,33,34,35,36,37,38,39,40]
    const arr = arr1.push(...arr2)
}

var testPush = function(abc) {
    var arr1 = [1,2,3,-1]
    var arr2 = [4,5,6,7,8,9,10,12,13,14,15,16,17,18,29,30,31,32,33,34,35,36,37,38,39,40]
    Array.prototype.push.apply(arr1, arr2)
}

var testPush2 = function(flag) {
    var arr1 = [1,2,3,-1]
    var arr2 = [4,5,6,7,8,9,10,12,13,14,15,16,17,18,29,30,31,32,33,34,35,36,37,38,39,40]
    arr1.push.apply(arr1, tslib.__spread(arr2));
}

var testConcat = function(abc) {
    var arr1 = [1,2,3,-1]
    var arr2 = [4,5,6,7,8,9,10,12,13,14,15,16,17,18,29,30,31,32,33,34,35,36,37,38,39,40]
    var arr  = arr1.concat(arr2)
  }

var testConcat = function(abc) {
    var arr1 = [1,2,3,-1]
    var arr2 = [4,5,6,7,8,9,10,12,13,14,15,16,17,18,29,30,31,32,33,34,35,36,37,38,39,40]
    var arr  = concat(arr1, arr2)
  }

var count = 1000000

var date = Date.now()
for (var i = 0; i < count; i++) {
  testPushES6()
}
// 136
console.log(Date.now() - date)

var date = Date.now()
for (var i = 0; i < count; i++) {
  testPush()
}
// 139
console.log(Date.now() - date)

var date = Date.now()
for (var i = 0; i < count; i++) {
  testPush2()
}
// 1005
console.log(Date.now() - date)

var date = Date.now()
for (var i = 0; i < count; i++) {
  testConcat()
}
// 310
console.log(Date.now() - date)

var date = Date.now()
for (var i = 0; i < count; i++) {
  testConcat2()
}
// 810
console.log(Date.now() - date)

Install tslib got error with the version of node v10.16.0

Hi, when I install tslib with Node v10.16.0 or higher version, got the error "Error: make failed with exit code", see the details in the picture below. However, it can be installed successfully with Node v6.11.1, would you please check the where is the problem. Thansk a lot!

image

"constructor" is enumerable when targetting es5

Hi, I've noticed that the behavior of "__extends" with regards to defining the "constructor" property is unexpected when you target "es5".

Try the following example in the TypeScript playground:

class TestSuper { }
class TestSub extends TestSuper { }

const properties = [];
for (const p in new TestSub()) {
    properties.push(p);
}
console.assert(properties.length === 0, "Should not have any enumerable properties");
console.assert(properties.indexOf("constructor") === -1, "Should not have constructor as an enumerable property");

If you compile this with ES2015, then classes and inheritance are natively supported, and running the code doesn't print anything to the console (as "constructor" isn't enumerable).
If you change the target to "es5", then you'll see stuff in the console, since "constructor" is now enumerable.

The fix should be easy, it's a matter of redefining __extends as follows:

    __extends = function (d, b) {
        extendStatics(d, b);
        function __() { Object.defineProperty(this, "constructor", { configurable: true, value: d, writable: true }); }
        d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
    };

Notice that the current implementation doesn't use defineProperty and is instead assigning the this.constructor member directly.

Is this a behavioral change that we'd like? I can submit a PR for it. But since it would be a breaking change, I don't know what would be the decision here.
As additional input, we've been using an updated version of __extends with this fix for several years in the Azure Portal.

Do you need to polyfill promises?

It seems like this library depends on window.Promise being available. Is that true? Are there any other requirements for this library?

v1.13.0 Error with older typescript version -- node_modules/tslib/tslib.d.ts(37,78): error TS2304: Cannot find name 'PropertyKey'. (When targeting es3)

Hi,

We are from the ApplicationInsights team and on updating the npm package to 1.13.0 we are now getting this error.
We are currently using ts v2.5.3 and as of today we cannot update to a later version because of issues with teams that consume our generated code.

Compiling...
Using tsc v2.5.3
common/temp/node_modules/tslib/tslib.d.ts(37,78): error TS2304: Cannot find name 'PropertyKey'.
common/temp/node_modules/tslib/tslib.d.ts(37,103): error TS2304: Cannot find name 'PropertyKey'.

Problem with tslib and ES modules

When Typescript compiler produces esm output, ex:

{
  "compilerOptions": {
    "target" : "esnext",
    "module": "esnext",
    "experimentalDecorators": true,
    "importHelpers": true,
  }
}

source test.ts

@foo()
class Bar {
}

dest test.js

import { __decorate } from "tslib";

let Bar = class Bar {
};

Bar = __decorate([
    foo()
], Bar);

Node 12/13 (which support esm natively) give error:

import { __decorate } from "tslib";
         ^^^^^^^^^^
SyntaxError: The requested module 'tslib' does not provide an export named '__decorate'

I seems to me, that Node treat tslint like as cjs module but his tslib.js does not contain standard cjs export.default expression.

TypeError: Cannot redefine property: default

Using Node 12.16.1, TypeScript 3.8.3, and tslib 1.12.0 I'm seeing this error:

/Users/phensley/dev/cldr-engine/node_modules/tslib/tslib.js:237
        Object.defineProperty(o, "default", { enumerable: true, value: v });
               ^
TypeError: Cannot redefine property: default
    at Function.defineProperty (<anonymous>)
    at /Users/phensley/dev/cldr-engine/node_modules/tslib/tslib.js:237:16
    at Object.__importStar (/Users/phensley/dev/cldr-engine/node_modules/tslib/tslib.js:246:9)
    at Object.<anonymous> (/Users/phensley/dev/cldr-engine/packages/cldr-compiler/lib/cli/compiler/index.js:4:21)

Occurs when __importStar is called:
import * as yargs from 'yargs';

Transpiled to:
var yargs = tslib_1.__importStar(require("yargs"));

Cannot extend String class in ES5

Reproduce here

We need to build a class extending from String class. But when we call toString() on the extended new class, we will see error:

VM85:24 Uncaught TypeError: String.prototype.toString requires that 'this' be a String
    at LazyJsonString.toString (<anonymous>)
    at LazyJsonString.deserializeJSON (eval at <anonymous> (main.js:513), <anonymous>:24:32)
    at eval (eval at <anonymous> (main.js:513), <anonymous>:41:15)
    at main.js:513

Can anyone kindly provide explanation to this error?

Related: aws/aws-sdk-js-v3#1004

declare module `'tslib'`

Right now, tslib.d.ts does not contain a module declaration for 'tslib' and instead declares the functions in the global namespace. As of TS 2.1.4, when I enable the --noEmitHelpers and --importHelpers compiler flags, my build fails because it cannot find the required 'tslib' module.

I'm opening an issue because there's probably a reason this hasn't been done already, but wouldn't it be possible to do something like:

// ... existing global typing defs
declare module 'tslib' {
  export function __extends(d: Function, b: Function): void;
  export function __assign(t: any, ...sources: any[]): any;
  export function __rest(t: any, propertyNames: string[]): any;
  export function __decorate(decorators: Function[], target: any, key?: string | symbol, desc?: any): any;
  export function __param(paramIndex: number, decorator: Function): Function;
  export function __metadata(metadataKey: any, metadataValue: any): Function;
  export function __awaiter(thisArg: any, _arguments: any, P: Function, generator: Function): any;
  export function __generator(thisArg: any, body: Function): any;
}

@billti @rbuckton @sandersn for visibility

module 'tslib' cannot be found

Hi guys. I'm getting this error when I run `node_modules/.bin/tsc' in the following folder.

error TS2354: This syntax requires an imported helper but module 'tslib' cannot be found.

The offending line (rxjs/Subscriber.d.ts(13,36) does indeed include an innocent looking extend keyword. Can you tell me what I'm doing wrong?

$ node_modules/.bin/tsc
node_modules/rxjs/Subscriber.d.ts(13,36): error TS2354: This syntax requires an imported helper but module 'tslib' cannot be found.

src/main.ts

import { Observable } from "rxjs";

Observable.timer(3000, 5000)
  .timeInterval()
  .subscribe((interval) => console.log(interval));

tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "importHelpers": true,
    "target": "es5",
    "noEmitHelpers": true
  }
}

package.json

{
  "name": "stuff",
  "version": "1.0.0",
  "scripts": {
    "build": "webpack"
  },
  "devDependencies": {
    "@types/core-js": "^0.9.35",
    "ts-loader": "^1.3.2",
    "typescript": "^2.1.4",
    "webpack": "^2.1.0-beta.25"
  },
  "dependencies": {
    "rxjs": "^5.0.1",
    "tslib": "^1.2.0"
  }
}

rxjs/Subscriber.d.ts(13)

export declare class Subscriber<T> extends Subscription implements Observer<T> {

I posted my question to stackoverflow but can't get any interest

__spread does not work in IE11

This TypeScript code (a Jasmine test):

describe("array spread operator", function() {
    it('should be able to spread arguments', function() {
        let argumentsArray;
        function testFunction() {
            argumentsArray = [...arguments];
        }
        (testFunction as any)(1, 2, 3);
        expect(argumentsArray).toEqual([1, 2, 3]);
    });
});

runs successfully in browsers but IE.
In IE11, it fails with:

Expected $.length = 1 to equal 3.
Expected $[0] = [object Arguments] to equal 1.
Expected $[1] = undefined to equal 2.
Expected $[2] = undefined to equal 3.

I can see the ... array spread operator gets built into a call for helper __spread, thus submitting the issue here.

Browsers I tried:

  • Chrome 76.0.3809.100 64bit
  • Opera 62.0.3331.116
  • Firefox Quantum 68.0.1 64-bit
  • Internet Explorer 11.309.16299.0
  • Microsoft Edge 41.16299.248.0

Two problems about tslib

Hello, handsome guy, please ask me some questions:

  1. You haven't released version 1.12.0 in NPM. Why can I install this version?

  2. in the version 1.12.0 I downloaded, why are the two integrity different? They are "integrity": "sha1-0fycrNBqFFbGLykCs2FXPoPWZHM=", "integrity": "sha1-yIHhPMcBWJTtkUhi0nZDb6mkcEM=". If the integrity is sha1-0fycrNBqFFbGLykCs2FXPoPWZHM=, my project will crash

Which files need to be hosted?

Hi @rbuckton ,
I am a member of cdnjs. We want to host this library.
I am not sure which files need to be hosted, and I guess tslib.js should be hosted.

Could you please confirm if there is any other file need to be added in cdnjs?
Thank you!

cdnjs/cdnjs#10128

es5 polyfill and tslib

Hi All,

There seems to be an issue with tslib once you try to use es5 polyfill.

As an example:
We are writing a code on ES3/AngularJS and deploy it to the back end that renders layout pages in IE8 compat. mode(some of big companies still do this due to legacy infra and stuff, ours is one of them).
This is a company system that we have no control over.
The only thing we are allowed to do is to upload files :) and we have to use stuff like RequireJS etc...

Basically this part is a bad check in our situation(along with some others in this file):
https://github.com/Microsoft/tslib/blob/3d0f4d4823605e6e82cf250b509d9a685c42ad41/tslib.js#L46-L56

because es5-shim would polyfill Object.create however defineProperty would fail on any IE due to compat. mode.

Would it not be better just to try catch or something along those lines?

Lint tslib

Helper style is somewhat inconsistent, and there are some trailing semicolons in some places but not others, for example in the es6 version:

export function __asyncValues(o) {
    if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined.");
    var m = o[Symbol.asyncIterator];
    return m ? m.call(o) : typeof __values === "function" ? __values(o) : o[Symbol.iterator]();
}

export function __makeTemplateObject(cooked, raw) {
    if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; }
    return cooked;
};

(__makeTemplateObject has an unneeded semicolon, __asyncValues right above it does not)

No matching version found for version 1.9.3

I'm trying to install version 1.9.3, a requirement for another package I'm installing, but I'm getting errors. 1.9.2 and 1.10.0 both install fine.

npm ERR! code ETARGET
npm ERR! notarget No matching version found for [email protected]
npm ERR! notarget In most cases you or one of your dependencies are requesting
npm ERR! notarget a package version that doesn't exist.

tslib__WEBPACK_IMPORTED_MODULE_0__ is not defined

when add "importHelpers": true, to my angular project i have

this error:
tslib__WEBPACK_IMPORTED_MODULE_0__ is not defined

my tsconfig :

{
"compileOnSave": false,
"compilerOptions": {
"baseUrl": "./",
"outDir": "./dist/out-tsc",
"sourceMap": true,
"declaration": false,
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"importHelpers": true,
"target": "es5",
"typeRoots": [
"node_modules/@types"
],
"lib": [
"es2017",
"dom"
]
}
}

and my package.json :

"dependencies": {
"@angular-redux/form": "^9.0.1",
"@angular-redux/router": "^9.0.0",
"@angular-redux/store": "^9.0.0",
"@angular/animations": "^6.0.3",
"@angular/common": "^6.0.3",
"@angular/compiler": "^6.0.3",
"@angular/core": "^6.0.3",
"@angular/forms": "^6.0.3",
"@angular/http": "^6.0.3",
"@angular/platform-browser": "^6.0.3",
"@angular/platform-browser-dynamic": "^6.0.3",
"@angular/router": "^6.0.3",
"@ng-bootstrap/ng-bootstrap": "^2.1.1",
"animatewithsass": "^3.2.1",
"bootstrap": "^4.1.1",
"bootstrap-sass": "^3.3.7",
"compass-mixins": "^0.12.10",
"core-js": "^2.5.4",
"flux-standard-action": "^2.0.3",
"jquery": "^3.3.1",
"redux": "^4.0.0",
"redux-logger": "^3.0.6",
"rxjs": "^6.0.0",
"tslib": "^1.9.3",
"zone.js": "^0.8.26"
},
"devDependencies": {
"@angular-devkit/build-angular": "~0.6.8",
"@angular/cli": "~6.0.8",
"@angular/compiler-cli": "^6.0.3",
"@angular/language-service": "^6.0.3",
"@types/jasmine": "~2.8.6",
"@types/jasminewd2": "~2.0.3",
"@types/node": "~8.9.4",
"codelyzer": "~4.2.1",
"jasmine-core": "~2.99.1",
"jasmine-spec-reporter": "~4.2.1",
"karma": "^2.0.3",
"karma-chrome-launcher": "~2.2.0",
"karma-coverage-istanbul-reporter": "~2.0.0",
"karma-jasmine": "~1.1.1",
"karma-jasmine-html-reporter": "^0.2.2",
"protractor": "~5.3.0",
"ts-node": "~5.0.1",
"tslint": "~5.9.1",
"typescript": "~2.7.2"
}

and in my component
import { select } from '@angular-redux/store';
@select() user;

Override helpers

Introducing support for tslib in TS 2.1 is great as we can now easily use up-to-date TS helpers without maintaining our own copy of the source files from github. 😄

But it also introduced a regression: the option to override TS helpers with our own seems to have been lost?

Specifically, I want to provide my own __extends because the one provided by TS is (deliberately) buggy.
Before I could do that by having a global __extends that would take precedence. With the new --importHelpers it seems that I lost this option.

What is the recommended way to go about that?

version 1.8.0 is breaking angular

I'm getting issues with 'reflect-metadata' not found, or Zone js not found, all kinds of import errors during runtime and tracked it down to the tslib update. Reverting package.json to 1.7.1 fixes the issue.

SHould this be reported here or angular?

__createBinding assumes exports are readonly

Using tslib 1.12.0, we are seeing the following error being thrown:

TypeError: Cannot set property foo of #<Object> which has only a getter

This is a result of this commit, which changes __exportStar to use __createBinding, which now uses Object.defineProperty to create a readonly property on exports.

The implication is that it's no longer possible to do this in TypeScript:

# module1
export function foo() { /* do something */ }

# module2
export * from 'module1';
export function foo() { /* do another thing */ }

This differs from CommonJS behavior, where it is possible to overwrite previous exports.

tslib triggers a process experimental warning in node.js 10.1.0

node.js 10.1.0 has moved the experimental version of the fs promises api to require('fs').promises

When tslib imports the fs module it loops over every exported variable which now triggers a process-wide warning which is logged to the console.

(node:78361) ExperimentalWarning: The fs.promises API is experimental

The stack when this happens is:

ExperimentalWarning: The fs.promises API is experimental
    at Object.get [as promises] (fs.js:84:15)
    at Object.__importStar (/Users/mdouglass/kixeye/km/server/km-sim/node_modules/tslib/tslib.js:213:100)
    at Object.<anonymous> (/Users/mdouglass/kixeye/km/server/km-sim/node_modules/@kixeye/km-shared/lib/protocols/index.ts:1:1)
    at Module._compile (internal/modules/cjs/loader.js:678:30)
    at Module._extensions..js (internal/modules/cjs/loader.js:689:10)
    at Object.require.extensions.(anonymous function) [as .js] (/Users/mdouglass/kixeye/km/server/km-sim/node_modules/ts-node/src/index.ts:395:14)
    at Module.load (internal/modules/cjs/loader.js:589:32)
    at tryModuleLoad (internal/modules/cjs/loader.js:528:12)
    at Function.Module._load (internal/modules/cjs/loader.js:520:3)
    at Module.require (internal/modules/cjs/loader.js:626:17)

__values causes an infinite loop on Sets when Symbol.iterator isn't defined

Environment: https://github.com/convoyinc/apollo-cache-hermes/tree/8088c19

Specifics:

Helpful reproduction repo built by @alexanderson1993 over in convoyinc/apollo-cache-hermes#382

When run on react-native android (and presumably older versions of Chrome), the following code infinite loops on tslib.__values (it emits undefined forever)

TypeScript source:

export class QueryInfo {
  // …
  public readonly variables: Set<string>;
  // …
  private _assertAllVariablesDeclared(messages: string[], declaredVariables: Set<string>) {
    for (const name of this.variables) {
      if (!declaredVariables.has(name)) {
        messages.push(`Variable $${name} is used, but not declared`);
      }
    }
  }
  // …
}

Emitted source:

// …
QueryInfo.prototype._assertAllVariablesDeclared = function (messages, declaredVariables) {
    try {
        for (var _a = tslib_1.__values(this.variables), _b = _a.next(); !_b.done; _b = _a.next()) {
            var name_1 = _b.value;
            if (!declaredVariables.has(name_1)) {
                messages.push("Variable $" + name_1 + " is used, but not declared");
            }
        }
    }
    catch (e_1_1) { e_1 = { error: e_1_1 }; }
    finally {
        try {
            if (_b && !_b.done && (_c = _a.return)) _c.call(_a);
        }
        finally { if (e_1) throw e_1.error; }
    }
    var e_1, _c;
};

// …

Observed: for (const name of this.variables) { loops forever, assigning undefined to name on each iteration

Document helpers needed per target platform

So, apparently we need these helpers (quite like polyfills) to target platforms, which don't have some of the newer features yet (like async/await). Ok.

However, if I target es2017, es2018 (or es2025 when it comes), tsc will produce code that doesn't need to rely on these helpers, and there's no need for this lib?

Would it make sense to document which helpers are required on which target, so I can judge if I need this library at all?

(Why external library? Why not just bundle this functionality into typescript, which already seems to have a copy of these helpers anyway - tslib is needed only to import the helpers instead of multiplying them now?)

__importStar can result in undefined imports when importing cyclical dependencies

I've run across what appears to be a bug with __importStar when cyclical dependencies are involved.

I've replicated the issue this sandbox:
https://codesandbox.io/s/eloquent-khayyam-nn14o?file=/src/tsFile.ts

Which contains 3 key files:

index.js

const jsFile = require("./jsFile");
jsFile.doMainThingInJsFile();
console.log("All is good!");

tsFile.ts

//this fails
import * as jsFile from "./jsFile";

//this works
// import jsFile = require("./jsFile");

export function doSomethingInTsFile() {
  console.log("tsFile.doSomethingInTsFile()");
  jsFile.doSomethingInJsFile2();
}

jsFile.js

const tsFile = require("./tsFile");

function doMainThingInJsFile() {
  console.log("jsFile: in doMainThingInJsFile()");
  tsFile.doSomethingInTsFile();
}
exports.doMainThingInJsFile = doMainThingInJsFile;
exports.doSomethingInJsFile2 = function() {
  console.log("jsFile.doSomethingInJsFile2()");
};

tsFile.ts and jsFile.js are cyclical dependencies.

When the 'fail' version of the code runs, doSomethingInTsFile() inside of tsFile.ts is undefined.

Looking at the source code for __importStar it becomes clear what is happening: the reference returned from require(...) is replaced with a new container object. It is unclear to me why this occurs and instead the original isn't used, but I suspect its related to emitting code that will ultimately work with other code that goes looking for a 'default' export in that output.

I would chalk this up to me misusing import * or other settings being incorrect, but if the cyclical dependency is removed, then the module imports just fine with an import *. It's this differing behaviour that leads me to think there is a bug here. We encountered this in our project when some code that rarely ran failed at runtime because a cyclical dependency had been added elsewhere that ultimately caused the member functions of the imported library (old commonjs code) to be undefined.

consider setting the __esModule marker in createExporter

Currently, the createExporter function does not set the '__esModule' flag on the exports object.

A recent override in the jspm/registry#1040 to support this library for [email protected]/[email protected] caused this package to fail under [email protected]/[email protected].
That issue, as reported in #26, was fixed for the latter scenario by @frankwallis in jspm/registry#1041 but naturally breaks the former scenario once again.

In attempting to find a fix that would work for both versions, I found that specifying the __esModule flag on the exports object in createExporter results in the correct behavior.

I'm not sure if this is the right way or the right place to resolve the issue.

See also microsoft/TypeScript#13709 and systemjs/systemjs#1587

TSLib 2.0.0 causing bundling issues

Hi there,

TSLib 2.0.0 seems to be causing bundling issues due to the use of exports as a parameter name in the __exportStar function.

Starting with v2 the export star function calls another function called __createBinding. When this is bundled a simple bundler will add exports. in front of the create binding call (which is a common technique in bundlers) but as there is a parameter called exports the call is referencing the incorrect variable.

Even TypeScript itself will generate similar code as shown here
https://www.typescriptlang.org/play/?experimentalDecorators=true&emitDecoratorMetadata=true&module=1&ssl=12&ssc=1&pln=9&pc=1#code/KYDwDg9gTgLgBANwIZTgfTQYysJNgBCAlgHYAmpA5nALxwDyARgFbCYwB02u+cA-HAAUAMwCuJdkQglBEADRwAtgoDWqgEwBKOAG8AUHENwiwoSvW0adcWWDDSwMtvO04KgNwGjTVuw637EmAABSgIMGBYAE9ZDQUdOGASUUVIpEYAG2AALjgYKFFgBUpgGFyxCRgpGW0EnBhRKBIlAG0VAF13OABfHs1Pbu1ckXFJaVilVQ1ar0MTMwsra3I7Byc3RbdPIzgINvV210U2zq9Bzz1QSFg4CrHmjCvoGABlGBRBZUTwZ4BnGZ2wmgQmQqDAxmaim080E4IAhFY4AAiAJIUQZGBIuAAMmxcDhT1gvw4AAskL96AB3EihcKRGAxMCabQYbh4QikCgkSiCQkwX4KL5MgZAA

I don't see a need for the parameter to be called exports so I think it would be acceptable to simply to change the parameter name to avoid this issue.

tslib __decorate was conflict with property decorator definition

such a code with property decorator usage:

class Controller {

	name = 'xx';

	@inject(Store)
	store: any = null;
}

after a tsc compiling:

var Controller = /** @class */ (function () {
        function Controller() {
            this.name = 'xx';
            this.store = null;
        }
        tslib_1.__decorate([
            inject_1.default(Store)
        ], Controller.prototype, "store", void 0);
        return Controller;
    }());

and here is the tslib __decorate implementation:
https://github.com/Microsoft/tslib/blob/b1ed5e1b940756d18609833caf9b781e9bc3984f/tslib.js#L85-L90
we can realize that if the property decorator return a descriptor, __decorate function will define property for us, from the code above.

but in typescript lib.es.d.ts definition, property decorator should not return anything:
https://github.com/Microsoft/TypeScript/blob/master/lib/lib.es6.d.ts#L1285

declare type PropertyDecorator = (target: Object, propertyKey: string | symbol) => void;

so which one is the truth?

This does not seem to work with JSPM anymore

@frankwallis @aluanhaddad
We're currently having some critical issues, which I think are related to jspm/registry#1040.

Basically, when installing tslib from NPM using JSPM v0.16.52, it seems to get confused about which file is an ES module and which isn't. When we did a jspm install this morning, it somehow ended up creating a jspm_packages/[email protected] file containing this:

export * from "npm:[email protected]/tslib.es6.js";
export {default} from "npm:[email protected]/tslib.es6.js";

Where previously, it contained this:

module.exports = require("npm:[email protected]/tslib.js");

Also, we end up with "format esm"; at the top of jspm_packages/[email protected]/tslib.js, where before it was "format cjs";. This makes no sense to me, as that file is clearly not an ES module, and System.js refuses to load this file, unless we enable client-side transpilation - which we won't.

I'm not really sure what is happening here, but it's breaking everything for us, which is a rather big problem.
Do you know what is going on here, and if so, can you provide a workaround until it's fixed? We can't update to the latest JSPM just yet, for various reasons, so we absolutely need this to work for JSPM 0.16.

tslib not working

tsconfig.json

{
"compilerOptions": {
"importHelpers": true
}
}

package.json

{
"name": "drag-and-drop",
"version": "0.0.1",
"license": "MIT",
"scripts": {
"build": "yarn clean && tsc",
"clean": "rimraf dist && rimraf build.js",
"build:amd": "yarn clean && tsc --outFile build.js --module amd",
"build:system": "yarn clean && tsc --outFile build.js --module system",
"build:umd": "yarn clean && tsc --module umd",
"build:commonjs": "yarn clean && tsc --module commonjs",
"watch:amd": "yarn clean && tsc --watch --outFile build.js --module amd",
"watch:system": "yarn clean && tsc --watch --outFile build.js --module system",
"watch:umd": "yarn clean && tsc --watch --module umd",
"watch:commonjs": "yarn clean && tsc --watch --module commonjs"
},
"devDependencies": {
"rimraf": "^3.0.2",
"typescript": "^3.8.3"
},
"dependencies": {
"lite-server": "^2.5.4",
"tslib": "^1.11.1"
}
}

app.ts

const obj = {
a: "Hello",
};

const obj2 = { ...obj, b: "World" };

console.log(obj2);

app.js (output)

var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var obj = {
a: "Hello"
};
var obj2 = __assign(__assign({}, obj), { b: "World" });
console.log(obj2);

Provide a sample demonstrating how tslib makes a difference

Please provide some samples demonstrating how tslib makes a difference. Expose scenarios: what javascript code differs between using importHelpers: true and importHelpers: false and how it differs exactly.

I also think there should be a clear answer to the question:
What does one win if he uses tslib instead of not using it?

v1.11.0 contains reference to WeakMap which is breaking older TypeScript version usages

We are getting the following error when our project "ApplicationInsights" auto upgrades to 1.11.0

Using tsc v2.5.3
common/temp/node_modules/tslib/tslib.d.ts(35,94): error TS2304: Cannot find name 'WeakMap'.
common/temp/node_modules/tslib/tslib.d.ts(36,94): error TS2304: Cannot find name 'WeakMap'.

We are currently blocked on upgrading to a later version of TypeScript and as a work around we have fixed this to version 1.10.0, is it possible to make 1.11.0 compatible with older versions of TS?

Add bower support to main repo

I'd like to use bower to consume the tslib repo. It looks like the bower version of this repo was already created a month ago: https://github.com/Draccoz/tslib. It'd be awesome if we could bring the bower and npm definitions of the repo into the same place, under the Microsoft org. I realize that since there is an existing bower definition, this might cause problems. In that case, is there any way we can set up a hook to submit a PR to the bower repo every time something gets merged to master here?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.