Giter Club home page Giter Club logo

rollup-plugin-typescript's Introduction

Moved

This module has moved and is now available at @rollup/plugin-typescript. Please update your dependencies. This repository is no longer maintained.

rollup-plugin-typescript

Build Status npm-version npm-monthly-downloads npm-dependencies

Seamless integration between Rollup and Typescript.

Why?

See rollup-plugin-babel.

Installation

npm install --save-dev rollup-plugin-typescript typescript tslib

Note that both typescript and tslib are peer dependencies of this plugin that need to be installed separately.

Usage

// rollup.config.js
import typescript from 'rollup-plugin-typescript';

export default {
  input: './main.ts',
  plugins: [
    typescript()
  ]
}

The plugin loads any compilerOptions from the tsconfig.json file by default. Passing options to the plugin directly overrides those options:

...
export default {
  input: './main.ts',
  plugins: [
      typescript({lib: ["es5", "es6", "dom"], target: "es5"})
  ]
}

The following options are unique to rollup-plugin-typescript:

  • options.include and options.exclude (each a minimatch pattern, or array of minimatch patterns), which determine which files are transpiled by Typescript (all .ts and .tsx files by default).

  • tsconfig when set to false, ignores any options specified in the config file. If set to a string that corresponds to a file path, the specified file will be used as config file.

  • typescript overrides TypeScript used for transpilation:

    typescript({
      typescript: require('some-fork-of-typescript')
    })
  • tslib overrides the injected TypeScript helpers with a custom version

    typescript({
      tslib: require('some-fork-of-tslib')
    })

TypeScript version

Due to the use of tslib to inject helpers, this plugin requires at least TypeScript 2.1. See also here.

Importing CommonJS

Though it is not recommended, it is possible to configure this plugin to handle imports of CommonJS files from TypeScript. For this, you need to specify CommonJS as the module format and add rollup-plugin-commonjs to transpile the CommonJS output generated by TypeScript to ES Modules so that rollup can process it.

// rollup.config.js
import typescript from 'rollup-plugin-typescript';
import commonjs from 'rollup-plugin-commonjs';

export default {
  input: './main.ts',
  plugins: [
    typescript({module: 'CommonJS'}),
    commonjs({extensions: ['.js', '.ts']}) // the ".ts" extension is required
  ]
}

Note that this will often result in less optimal output.

Issues

This plugin will currently not warn for any type violations. This plugin relies on TypeScript's transpileModule function which basically transpiles TypeScript to JavaScript by stripping any type information on a per-file basis. While this is faster than using the language service, no cross-file type checks are possible with this approach.

This also causes issues with emit-less types, see #28.

rollup-plugin-typescript's People

Contributors

arlair avatar awerlang avatar crowdhailer avatar danielruf avatar dmitrage avatar eventualbuddha avatar lukastaegert avatar maxdavidson avatar naridal avatar notwoods avatar pkozlowski-opensource avatar raviqqe avatar rich-harris avatar rreverser avatar samcooke98 avatar shellscape avatar stefanullinger avatar timocov avatar tolu avatar trysound avatar victorystick 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

rollup-plugin-typescript's Issues

File extensions / JSX

I'm porting a Typescript project over to Rollup, and am hoping to use this plugin to make the compile process straightforward. I'm facing two issues which I can't see referenced in the docs:

  • JSX. I seem to get syntax errors on lines with JSX syntax. Is this supported?
  • File extensions. It seems I have to alter my imports to have a file extension, otherwise I get an error saying the file wasn't found. Is there a way around this?

Here is my config:

var typescript = require('rollup-plugin-typescript');
var ts = require('typescript');

module.exports = {
    entry: 'src/index.tsx',
    dest: 'dist/test.js',
    format: 'es6',
    plugins: [
        typescript({
            target: ts.ScriptTarget.ES2015,
            jsx: "react"
        })
    ]
};

Allow modular use of emit-less types

A regular TypeScript compilation takes many modules into consideration at once. It manages imports and exports of types as well as values, where as ECMAScript is only concerned with values. TypeScript only uses the type information of emit-less types like interface, type, const enum etc. during compilation and discards these from the final emit; they simply won't exist in the output.

This poses a problem since Rollup processes modules in the order they're encountered. Any module transforms have to be done without any information about its dependencies (except for some rare cases with circular dependencies). We simply cannot know if an imported identifier is an emit-less type or a value that is preserved. When Rollup later attempts to hook up the imports of one file with the exports of another, it will complain that the imports for these emit-less types don't have any corresponding exports.

Import and use of a const enum

This means that any import and usage of a const enum defined in another module will fail.

// some-enum.ts
export const enum Foo { bar, baz } // results in the empty string after transpilation

// main.ts
import { Foo } from './some-enum';
  // Rollup -> Error: Module some-enum.ts does not export Foo (imported by main.ts)

console.log( Foo.bar );

What we would want is for the import statement above to be completely removed since no actual value is imported, and for Foo.bar to be replaced with the constant value it corresponds to.

Re-export of an emit-less type

A re-export of a type will fail since the module doing the re-export cannot know that what is being exported doesn't exist except during compilation.

export { Foo } from './some-enum';
  // Rollup -> Error: 'Foo' is not exported by 'some-enum.ts' (imported by main.ts)

In this case, we'd just like the export statement to be removed.

Summary

To be useful in practice the plugin must gracefully handle:

  • imports and usages of const enums defined in other modules
  • re-exports of emit-less types

These problems can only be solved by having TypeScript process several modules simultaneously. Unfortunately, this doesn't fit well with Rollup's current behaviour of processing modules in turn as they're encountered.

Hopefully someone might be able to bring some good insights as to how to solve this problem.

Typescript 1.8.x

Hi,

I would like to use your plugin with Typescript 1.8.x, so I tried

import typescript from 'rollup-plugin-typescript';
import * as ts from 'typescript';

export default {
    ...
    plugins: [
        typescript( {
            target: ts.ScriptTarget.ES6,
            typescript: ts
        } )
    ]
}

Unfortunately, there is a change in the API that is not compatible with your current code, as the host is getting passed as the third parameter instead of the fourth.

What would be the best way to fix this?!
I can submit a PR, if you like... but wanted to discuss the best way before.

Kind regards,
Stefan

No type checking - Ignores errors in the code

With default TSC you can't transpile if there are issues in the code. With this plugin everything seems to be transpiled even with errors. No default type checking?

Example

function foo(name: string): void {}
foo([]); // array and valid with this plugin

In VSCode I get this message: Argument of type 'never[]' is not assignable to parameter of type 'string'.

But Rollup ignores it and bundle just fine!

Phantom Error when trying to compile with target ES6

I have a small project that i am compiling with rollup in multiple ways - basically I compile an output file for every possible target. They all compile and work just fine, except when I use ES6 as a target, in which case it tells me that it finds an Unexpected token (7:50) in a file, but line 7 doesnt even have 50 columns in that file. Tinkering with the any of the files of that project does not change the reported location of the error. All other targets work, using tsc directly works without error as well. I also have used the same rollup config on another project where all the compiles work just fine.

Can you hint me towards debugging this maybe? Is there any kind of verbose mode for rollup so that i can get more context for the error it finds?

Recurring problem with imports

This problem lies at the intersection between this plugin and rollup-plugin-commonjs, I believe, but it's a serious problem and doesn't happen without TypeScript, so I'm filing it here.

If you use TypeScript and you import a package that's expecting to be used as a function (like socket.io-client or marked), you need to import it like this:

import * as marked from "marked";
import * as io from "socket.io-client";

...but when imported that way, Rollup will consider marked and io to be namespaces, and you can't call the function that they represent.

If you try:

import marked from "marked";
import io from "socket.io-client";

or

import { marked } from "marked";
import { io } from "socket.io-client";

TypeScript will throw an error based on the standard way that TypeScript definition files are written for both of these packages. The latter probably wouldn't work anyway, since both are exported as the default export.

I get that Rollup is trying to be "correct" in an ES6 import way, but we need Rollup to Just Work here and not care that, even though we're using the first import syntax, the item we're importing is actually a raw JavaScript object that can be called as a function, if necessary.

Currently there's no way that I've found to make these imports work correctly without hacking the type files and sometimes the original package code directly. If there's a way to override Rollup and tell it to just give me the entire exported object without wrapping it in a frozen object, I haven't found it.

So for completeness: If I have a project that is using rollup-plugin-typescript AND rollup-plugin-commonjs AND rollup-plugin-node-resolve, and I want to import a package like "marked" (npm install marked @types/marked), there's no current way to do this, because the normal way to use marked is:

let marked = require("marked");
let result = marked("some markdown here");

And, as far as I can tell, there's no way to get that equivalent functionality in a way that both TypeScript and Rollup will work with.

Different behaviour for importing typescript modules to importing js modules

I have two comments here. They might both be by design but both confused me.

I am bundle jasmine tests using rollup. Before changing to typescript the following worked very nicely with javascript

import * as vector_test from "./vector_test";

describe("Level Application; ", function() {

  it("it should have a working test", function() {
    expect(true).toEqual(true);
  });
});

However I had to make some unexpected changes to switch to using typescript. There were

  1. requiring a file extension. would it be possible/advisable for bundling ts files to look for more ts files by default
  2. I actually have to use the import otherwise it is not included. This seams confusing seeing as it is not the case with the js version
/// <reference path="./jasmine.d.ts" />
import * as vector_test from "./vector_test.ts"; 
vector_test

describe("Level Application; ", function() {

  it("it should have a working test", function() {
    expect(true).toEqual(true);
  });
});

Support JSX

Add tests that ensure the plugin can handle jsx expressions (see #11).

Typescript decorator when exporting module with default class tries to set values on "exports" and throws

Rollup config:

import typescript from 'rollup-plugin-typescript';

export default {
  entry: './main.ts',
  moduleName: 'MainTest',
  plugins: [
    typescript({
      typescript: require('typescript')
    })
  ],
  targets: [
    {
      dest: 'output.js',
      format: 'iife',
    },
  ]
}

main.ts

import {MyDecorator} from "./my-decorator";

@MyDecorator
export default class MainTest {

}

my-decorator.ts

export function MyDecorator(constructor: Function) {
    console.log('Decorator');
}

Output - exports is being used, but isn't passed into the IIFE:

var MainTest = (function () {
'use strict';

function __decorate(decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
}

function MyDecorator(constructor) {
    console.log('Decorator');
}

exports.default = (function () {
    function MainTest() {
    }
    return MainTest;
}());
exports.default = __decorate([
    MyDecorator
], exports.default);

return exports.default;

}());

If you remove default from main.ts, you'll get code that works, but this setup throws.

Overriding TypeScript version

Docs are stating that TS version used by this plugin can be easily overridden giving this code snippet as an example:

import typescript from 'rollup-plugin-typescript';
import * as ts from 'typescript';

export default {
  entry: 'main.ts',

  plugins: [
    typescript({
      target: ts.ScriptTarget.ES6
      sourceMap: true
    })
  ]
}

Is importing import * as ts from 'typescript'; enough to override tsc version? If so, what kind of node black magic would be involved here? I've played with this locally and couldn't override TS version.

Is there are clever trick at play here or is the override option missing from the impl?

Is this strategy for TS integration in rollup viable?

So, I'm playing with this plugin and started to hit various transpilation problems (mostly around classes not ES6-exported properly. So I've started to dig into the source of those pbs and it turns out that by default tsc doesn't allow ES6 module with ES5 target combination of options. If you try to combine those 2 options together you get:

error TS1204: Cannot compile modules into 'es2015' when targeting 'ES5' or lower.

So it seems, on the surface, that tsc is not meant to output ES5 while preserving ES6 import / exports...

I guess that we are not getting this error from rollup since we are calling typescript.transpileModule where the check might be omitted (?)

cc: @robwormald

Specify tsconfig.json file

It doesn't appear that there is any way to specify a custom tsconfig.json path/name.

For example, my project has 2, and the one I want to point this plugin at is called "tsconfig_jit.json".

Would be clean and super handy :)

Incremental compilation and rewriting plugin

This plugin seems useless in current state โ€” it much better to build TypeScript separately and use Rollup only for bundle JS files.

But it hard because there is no oficial option to use Rollup with Gulp, where we can use https://github.com/ivogabe/gulp-typescript โ€” it is a good implementation of plugin for build TypeScript.

We need a full support of TypeScript with TS Language Service API and incremental compilation, that is important for develop with watch option.

Currently we should to use some external utils, like rollup-plugin-gulp (that didn't work for me), or use SystemJS to load ES modules directly and build production bundle from these files.
But all these things must be inside this plugin โ€“ just plug and work.

Typescript ES6 Module Resolution on Windows

Hello,

Great work on this project! We are just exploring rollup, specifically in combination with typescript. We are having a small issue. I am not sure if it is with Rollup itself or the Typescript plugin. We have a few developers. For those on a mac, the project works fine. On a Windows machine we are getting the following error:

events.js:141
     throw er; // Unhandled 'error' event
     ^
Error: Could not resolve ./B from C:\Users\Cameron\source\git\typescript\src\main\ts\C.ts
   at C:\Users\Cameron\source\git\typescript\node_modules\gulp-rollup\node_modules\rollup\dist\rollup.js:7701:37
   at tryCatch (C:\Users\Cameron\source\git\typescript\node_modules\gulp-rollup\node_modules\rollup\dist\rollup.js:337:12)
   at invokeCallback (C:\Users\Cameron\source\git\typescript\node_modules\gulp-rollup\node_modules\rollup\dist\rollup.js:349:13)
   at publish (C:\Users\Cameron\source\git\typescript\node_modules\gulp-rollup\node_modules\rollup\dist\rollup.js:320:7)
   at flush (C:\Users\Cameron\source\git\typescript\node_modules\gulp-rollup\node_modules\rollup\dist\rollup.js:131:5)
   at nextTickCallbackWith0Args (node.js:419:9)

We are using gulp. Here is the gulpfile:

var gulp = require('gulp');

var del = require('del');
var rename = require('gulp-rename');

var rollup = require('gulp-rollup');
var rollupTypescript = require('rollup-plugin-typescript');

var sourcemaps = require('gulp-sourcemaps');
var uglify = require('gulp-uglify');


gulp.task('build', function () {
  return gulp.src('src/main/ts/C.ts', {read: false})
    .pipe(rollup({
      format: 'iife',
      moduleName: 'libraryname',
      sourceMap: true,
      plugins: [
        rollupTypescript()
      ]
    }))
    .pipe(rename("rollup-test.js"))
    .pipe(sourcemaps.write("."))
    .pipe(gulp.dest("build"));
});

gulp.task('dist', ["build"], function () {
  return gulp.src('build/*.js')
    .pipe(uglify())
    .pipe(rename({
      extname: '.min.js'
    }))
    .pipe(gulp.dest('dist'));
});

gulp.task('clean', function (cb) {
  return del(["build", "dist"], cb);
});

gulp.task('default', ["build"]);

and the tsconfig.json:

{
  "compilerOptions": {
    "target": "es6",
    "module": "es6",
    "preserveConstEnums": true,
    "sourceMap": true,
    "declaration": true,
    "listFiles": true
  },
  "exclude": [
    "node_modules",
    "build",
    "dist"
  ]
}

and the pacakge.json

{
  "name": "typescript-test",
  "version": "1.0.0",
  "description": "typescript test",
  "tags": [
    "typescript",
    "es6"
  ],
  "author": "",
  "homepage": "",
  "repository": {
    "type": "",
    "url": ""
  },
  "bugs": "",
  "scripts": {
    "build": "gulp"
  },
  "dependencies": {},
  "devDependencies": {
    "del": "^1.2.0",
    "gulp": "^3.9.0",
    "gulp-rename": "^1.2.2",
    "gulp-rollup": "^1.7.0",
    "gulp-sourcemaps": "^1.6.0",
    "gulp-uglify": "^1.2.0",
    "rollup-plugin-typescript": "^0.5.0",
    "uglify-js": "^2.4.16"
  }
}

Here are the three classes:

src/main/ts/A.ts

import BClass from "./B";

export default class AClass {
  constructor(public b: BClass) {
    var foo = new BClass(this);
  }
}

src/main/ts/B.ts

import AClass from "./A";
export default class BClass {
  constructor(public foo: AClass) {
    console.log(foo.b);
  }
}

src/main/ts/C.ts

import BClass from "./B";
import AClass from "./A";

export default class CClass extends BClass {
  constructor(public a: AClass) {
    super(a);
    var foo = new AClass(this);
  }
}

Again this seems to work fine on Macs but doesn't work on at least two separate windows machines (the only two we have tried). They both fail with the same error.

TypeScript Helpers aren't processed by later plugins

I just had an issue where I was getting a crash on older browsers, and I traced it to this bit of code from the TypeScript helpers:

const __assign = Object.assign || function (target) {
    for (var source, i = 1; i < arguments.length; i++) {
        source = arguments[i];
        for (var prop in source) {
            if (Object.prototype.hasOwnProperty.call(source, prop)) {
                target[prop] = source[prop];
            }
        }
    }
    return target;
};

This is how the code looked in the final output, including the ES6 const keyword, even though I was running the code through the rollup-buble-plugin:

    plugins: [
        json(),
        typescript({
            typescript: require('typescript'), // TypeScript 2.1.5
        }),
        nodeResolve({
            jsnext: true, 
            browser: true,
            extensions: [ '.js', '.json', '.ts' ], 
            sourceMap: true,
            preferBuiltins: false
        }),
        commonjs({
            extensions: [ '.js', '.ts' ],
            namedExports: {
                "javascript-astar": [ "Graph", "astar" ],
                "screenfull": [ "request" ],
                "marked": ["Renderer","setOptions","parse"],
            }
        }),
        buble({transforms: { dangerousForOf: true, dangerousTaggedTemplateString: true }})
    ]

All the other TypeScript output was correctly being run through Buble, but not this one excerpt.

I've worked around it by adding these lines to my tsconfig.json:

        "noEmitHelpers": true,
        "importHelpers": true,

...so TypeScript is importing its own helpers now, and the TypeScript helpers from rollup-plugin-typescript are being stripped by Rollup. But it seems like the way the "helpers" are being injected is preventing the helpers from being run through later plugins.

I'm doing this two step transpile (TypeScript creating ES6, Buble creating ES5) for better import behavior. I'm not sure if there's a better way where all of the Node imports still work as expected (and can include ES6 code from node_modules), but this is what I've come up with.

In any event, I've listed my workaround, and I'm not going to personally dig into this any more.

`import xxx = require('xxx')` seems to be silently removed

Versions

rollup.config.js

const commonjs          = require('rollup-plugin-commonjs')
const nodeRes           = require('rollup-plugin-node-resolve')
const typescript        = require('rollup-plugin-typescript')

module.exports = {
  entry    : './src/api/test.ts',
  format   : 'cjs',
  dest     : './.building/api/test.js',
  treeshake: false,
  plugins  : [
    typescript({
      typescript: require('typescript'),
    }),
    commonjs(),
    nodeRes({
      extensions: ['.ts', '.js', '.json'],
    }),
  ],
}

test.ts (input)

// Start

import lodash = require('lodash')
console.log(lodash)

// End

test.js (output)

// Above are typescript helpers, like `__assign`, `__awaiter`, etc....

// Start
console.log(lodash);
// End

How to handle *.d.ts

Should we strip import with them or handle somehow?
allowJs doesn't work with node_modules, which does not let to use typescript as transpiler for angular2 dependencies.
Maybe better to lay on rollup-plugin-node-resolve with some cases?

Include typescript libs

Hi,

When I install the typings @types/whatwg-fetch, I get errors that types are missing which are defined in typescript's lib.d.ts file:

[2017-01-10 10:31:20.448] [ERROR] config - [project-root]/node_modules/@types/whatwg-fetch/index.d.ts (11,27): Cannot find name 'window'.
[2017-01-10 10:31:20.450] [ERROR] config - [project-root]/node_modules/@types/whatwg-fetch/index.d.ts (31,25): Cannot find name 'Blob'.
[2017-01-10 10:31:20.451] [ERROR] config - [project-root]/node_modules/@types/whatwg-fetch/index.d.ts (31,64): Cannot find name 'FormData'.
[2017-01-10 10:31:20.451] [ERROR] config - [project-root]/node_modules/@types/whatwg-fetch/index.d.ts (36,21): Cannot find name 'Blob'.
[2017-01-10 10:31:20.451] [ERROR] config - [project-root]/node_modules/@types/whatwg-fetch/index.d.ts (37,25): Cannot find name 'FormData'.

I'm using typescript 2.1.4.

This is my rollup configuration:

import typescriptPlugin from "rollup-plugin-typescript";
import nodeResolve from 'rollup-plugin-node-resolve';
import commonjs from 'rollup-plugin-commonjs';
import typescript from "typescript";

export default {
  entry: "./src/index.ts",
  format: "iife",
  dest: `dist/bundle.js`,
  plugins: [
    typescriptPlugin({
      typescript
    }),
    nodeResolve(),
    commonjs()
  ]
}

Any idea why the core types are not included?

Tests failed with Rollup 0.34.1

rollup-plugin-typescript tests failed with newest rollup version.

"devDependencies": {
    "mocha": "^2.3.3",
    "rollup": "^0.34.1",
    "rollup-plugin-typescript": "^0.7.6"
  }

Npm log:

$ npm install

> rollup-plugin-typescript@0.7.6 prepublish D:\test\rollup-plugin-typescript
> npm run test


> rollup-plugin-typescript@0.7.6 pretest D:\test\rollup-plugin-typescript
> npm run build


> rollup-plugin-typescript@0.7.6 prebuild D:\test\rollup-plugin-typescript
> rm -rf dist/*


> rollup-plugin-typescript@0.7.6 build D:\test\rollup-plugin-typescript
> npm run build:cjs && npm run build:es6


> rollup-plugin-typescript@0.7.6 build:cjs D:\test\rollup-plugin-typescript
> rollup -c -f cjs -o dist/rollup-plugin-typescript.cjs.js

Treating 'path' as external dependency
Could not resolve ./string from D:\test\rollup-plugin-typescript\src\index.ts
Error: Could not resolve ./string from D:\test\rollup-plugin-typescript\src\index.ts
    at D:\test\rollup-plugin-typescript\node_modules\rollup\src\Bundle.js:244:41
    at process._tickCallback (internal/process/next_tick.js:103:7)
    at Module.runMain (module.js:577:11)
    at run (bootstrap_node.js:352:7)
    at startup (bootstrap_node.js:144:9)
    at bootstrap_node.js:467:3
Type rollup --help for help, or visit https://github.com/rollup/rollup/wiki```

Cannot convert undefined or null to object, when pointing to ts file

This project is throwing this error Cannot convert undefined or null to object

The file is definitely there.

screen shot 2016-12-20 at 18 41 10

TypeError: Cannot convert undefined or null to object
    at Object.<anonymous> (/Users/nikos/WebstormProjects/solar-popup/rollup.config.js:9:23)
    at Module._compile (module.js:570:32)
    at Object.require.extensions..js (/Users/nikos/.nvm/versions/node/v6.9.1/lib/node_modules/rollup/bin/rollup:761:8)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.require (module.js:497:17)
    at require (internal/module.js:20:19)
    at /Users/nikos/.nvm/versions/node/v6.9.1/lib/node_modules/rollup/bin/rollup:768:19
    at process._tickCallback (internal/process/next_tick.js:103:7)```

TypeScript helpers are needlessly duplicated

When importing more than one class from separate files the __extends helper is needlessly duplicated. Bundling main.ts below

// main.ts
export { A } from './A';
export { B } from './B';

// Base.ts
export default class Base {}

// A.ts
import Base from './Base';
export class A extends Base {}

// B.ts
import Base from './Base';
export class B extends Base {}

yields

var Base = (function () {
    function Base() {
    }
    return Base;
})();

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var A = (function (_super) {
    __extends(A, _super);
    function A() {
        _super.apply(this, arguments);
    }
    return A;
})(Base);

var __extends$1 = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var B = (function (_super) {
    __extends$1(B, _super);
    function B() {
        _super.apply(this, arguments);
    }
    return B;
})(Base);

export { A, B };

We should not include duplicate helpers.

Ignore `declaration` setting in `tsconfig.json`

I have declaration set to true in my tsconfig.json file so I can generate and distribute typings with my library for others consuming the individual modules. (I invoke the TypeScript compiler separately to produce the typings; it wouldn't make sense for rollup-plugin-typescript to generate them for me.)

The TypeScript plugins for Browserify and Webpack seem to ignore this setting, but rollup-plugin-typescript passes it to the TypeScript compiler, resulting in the following error message:

Error loading /Users/jvilk/Code/browserfs/src/browserify_main.ts: Debug Failure. False expression: Unexpected multiple outputs for the file: '/Users/jvilk/Code/browserfs/build/node/browserify_main.d.ts'

After Googling a bit, it appears that this is a limitation of the TypeScript compiler's transpileModule method. Overriding the declaration field to false fixes the problem.

I think it would be great if you chose to do one of the following things:

  • Ignore the declaration setting, as it does not appear to be applicable. (But maybe I'm missing a scenario where it would be?), or...
  • Preemptively throw a more intelligible error when declaration is set to true.

Remove Typescript from dependencies

Is it possible to remove Typescript from dependencies, so it's not bound to a specific version, and it's possible to use Typescript 2.0.0.

Handling export with namespace

Hi, since initial release, the fix function tried to handle the "TypeScript's broken handling of export class"

With typescript 2.0.3, i can compile this code without problem :

export namespace Engine {
    export class Html {
        constructor() {

        }
        render() {
            console.log('Html engine render');
        }
    }
};

and get this

"use strict";
var Engine;
(function (Engine) {
    class Html {
        constructor() {
        }
        render() {
            console.log('Html engine render');
        }
    }
    Engine.Html = Html;
})(Engine = exports.Engine || (exports.Engine = {}));

with version 0.8.1 i get this :

var Engine;
(function (Engine) {
    var Html = (function () {
        function Html() {
        }
        Html.prototype.render = function () {
            console.log('Html engine render');
        };
        return Html;
    }());
})(Engine || (Engine = {}));

export { Engine, Html };

Is it normal to export Engine namespace if there is nothing in it ?

Property shorthand does not transpile

I demoed it in the following gist

So basically this

const f = val => ({ val })

should transpile to

var f = function (val) { return ({ val: val }); };

but transpiles to

var f = function (val) { return ({ val }); };

Edit

Renamed Destructuring to Property shorthand

Doesn't work with "strictNullChecks"

Hey.

TypeScript version: 1.9.0-dev.20160613-1.0.

If I set strictNullChecks in the tsconfig.json to a boolean value, and not using any configuration in the plugin - typeScript({}) - it throws this: Unknown compiler option strictNullChecks.

If I add some configuration to this, and set target to es5 and module to es6 plus set declaration to false within the plugin itself, and set it to use the TC 2 dev. Everything works.

The performance seems to getting worse also comparing to native TSC when you set the TS inline as an plugin option. 4 - 5 ms vs 2 - 3 ms native.

For me it seems that this plugin doesn't work with latest TS 2.0 Pre version? And I think this is the source for the issue? https://github.com/rollup/rollup-plugin-typescript/blob/master/package.json#L34

This plugin also uses itself as a dev dependency with a much older version of the plugin, and older version of Rollup.

Fails when exporting an abstact class

This case wasn't covered by #18

export abstract class A {}

which results in this code.

var A = (function () {
    function A() {
    }
    return A;
})();
A = A;

Rollup notices that nothing is exported and that there are no side-effects.The result is the empty bundle.

Usage examples in the readme

This might be a silly question.

I can't get the usage examples to work as show on this repo's README.

The problem I get is SyntaxError: Unexpected token import

When I rewrite the example to use the commonjs module format It all works properly. The version of node I am running is v5.1.0

I assume that my version of node does not yet support es6 module syntax. But I have updated it to the latest. I have tried running the example using the --harmony_modules, which also does not work.

Should the examples work with default node?
Or are the code examples actually in typescript and you are running them via tsc?
Or is there an es6 compile step necessary to run the example code?

Interface Export Throws Error

Hello, if I declare an interface and import it for use (implementation is done elsewhere) I receive an error that the module where the interface is declared does not export the interface when I run my rollup.
Module C:/Project/app/shared/search-modal.service.ts does not export ISearchModalService (imp
orted by C:/Project/app/shared/search-modal.component.ts)

I was unable to find any issue related to this in the plugin issues or on Stack Overflow, forgive me if this was the wrong location to make this. I know that interfaces are development time only and not concrete, and I would like to be able to leverage their usefulness in separating declaration and implementation and gain the benefits of using rollup to bundle my code for deployment. Worst case scenario, I suppose I make my interfaces classes and override them.

search-modal.service.ts:

import { ColumnDefinition } from "./column-definition";
import { Observable } from "rxjs/Observable";

export interface ISearchModalService {
    searchUrl: string;
    search(searchTerm: string, page?: number): Observable<any>;
    filterName: string;
    includePaging: boolean;
}

search-modal.component.ts pertinent line:
import { ISearchModalService } from "./search-modal.service";

tsconfig:

{
  "compileOnSave": true,
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false,
    "suppressImplicitAnyIndexErrors": true
  },
  "exclude": [
    "node_modules", "typings"
  ] 
}

rollup config file:

// rollup.config.js
import typescript from 'rollup-plugin-typescript';
import commonjs from 'rollup-plugin-commonjs';

// Custom Rollup Plugin to resolve rxjs deps
// Thanks to https://github.com/IgorMinar/new-world-test/blob/master/es6-or-ts-bundle/rollup.config.js
class RollupNG2 {
    constructor(options){
        this.options = options;
    }
    resolveId(id, from){
        if(id.startsWith('rxjs/')){
            return `${__dirname}/node_modules/rxjs/${id.replace('rxjs/', '')}.js`;
        }
    }
}
const rollupNG2 = (config) => new RollupNG2(config);

export default {
    entry: 'Areas/Epd/app/main.ts',
    dest: 'dist/bundle.es2015.js',
    format: 'iife',
    sourceMap: true,

    plugins: [
        typescript(),
  rollupNG2(),
  commonjs({ // https://github.com/rollup/rollup-plugin-commonjs
      exclude: ['node_modules/@angular/**', 'node_modules/rxjs', 'node_modules/@ng-bootstrap/**'],
      ignoreGlobal: false,
      sourceMap: false
  })
],
 // This is how you exclude code from the bundle
external: [
  '@angular/core',
  '@angular/common',
  '@angular/compiler',
  '@angular/core',
  '@angular/http',
  '@angular/platform-browser',
  '@angular/platform-browser-dynamic',
  '@ng-bootstrap/ng-bootstrap',
  'angular2-toaster', 'ng2-toastr'
],
// This is how you link the referenced module ids to the
// global variables exposed by the vendor bundle.
globals: {
    '@angular/core': 'vendor._angular_core',
    '@angular/http': 'vendor._angular_http',
    '@angular/platform-browser-dynamic': 
    'vendor._angular_platformBrowserDynamic',
}
}

Given that interfaces are a TypeScript feature I am wondering if either my set up in the rollup config is incorrect or if this is simply missing from the plugin.

Angular2 app bundling: errors from tippex

Today I've manged to go though all the steps of packaging an Angular2 application with Rollup but had to resort to few hacks, one of the problems being Rich-Harris/tippex#1.

I'm opening the issue here as maybe we can find another solution not involving tippex (or even if it is fixed on the tippex side we still need a test case + version bump).

Cannot compile Vega-Lite Typescript project

With this configuration

import typescript from 'rollup-plugin-typescript';
import * as ts from 'typescript';

export default {
  entry: './src/vl.ts',
  format: 'umd',

  plugins: [
    typescript({
      target: ts.ScriptTarget.ES6,
      typescript: require('typescript')
    })
  ]
}

I get this error

Could not load foo/vega-lite/src/node_modules/datalib/src/util.ts (imported by foo/vega-lite/src/util.ts): ENOENT: no such file or directory, open 'foo/vega-lite/src/node_modules/datalib/src/util.ts'
Error: Could not load foo/vega-lite/src/node_modules/datalib/src/util.ts (imported by foo/vega-lite/src/util.ts): ENOENT: no such file or directory, open 'foo/vega-lite/src/node_modules/datalib/src/util.ts'
    at /usr/local/lib/node_modules/rollup/www/ROLLUP/rollup/src/Bundle.js:162:11
    at tryCatch (/usr/local/lib/node_modules/rollup/www/ROLLUP/rollup/node_modules/es6-promise/lib/es6-promise/-internal.js:185:12)
    at invokeCallback (/usr/local/lib/node_modules/rollup/www/ROLLUP/rollup/node_modules/es6-promise/lib/es6-promise/-internal.js:197:13)
    at publish (/usr/local/lib/node_modules/rollup/www/ROLLUP/rollup/node_modules/es6-promise/lib/es6-promise/-internal.js:168:7)
    at publishRejection (/usr/local/lib/node_modules/rollup/www/ROLLUP/rollup/node_modules/es6-promise/lib/es6-promise/-internal.js:118:3)
    at flush (/usr/local/lib/node_modules/rollup/www/ROLLUP/rollup/node_modules/es6-promise/lib/es6-promise/asap.js:87:5)
    at doNTCallback0 (node.js:428:9)
    at process._tickCallback (node.js:357:13)
    at Function.Module.runMain (module.js:459:11)
    at startup (node.js:136:18)
Type rollup --help for help, or visit https://github.com/rollup/rollup/wiki

Rollup tries to load a .ts file from the wrong root. Instead of foo/vega-lite/src/node_modules/datalib/src/util.ts rollup is supposed to load foo/vega-lite/node_modules/datalib/src/util.js

Is there a way to specify the root of the search for node modules as well as a way to tell rollup to load js files instead of ts files?

My code is at https://github.com/vega/vega-lite/tree/dom/rollup

Plugin doesn't output non-fatal errors.

So right now plugin is able to forward any errors that break Typescript compilation but it doesn't output any other like types incompatibility etc. I just set up simple project with single input file and while tsc compiler properly reports this errors, compilation using rollup and this plugin stays silent. Is this the desired behavior?

I found this test repo: https://github.com/cetra3/rollup-ts-test. You can add something simple to app/main.ts file like:

var foo:Number = 'bar';

Rollup will display nothing while tsc main.ts will give:

main.ts(8,5): error TS2322: Type 'string' is not assignable to type 'Number'.

Typescript module import is broken since Rollup 0.34.0

Since version 0.34.0, rollup requires file extensions when importing modules.

However, ".ts" extension should not be used when importing typescript modules, for example:
import { AppModule } from './app.module';
see https://www.typescriptlang.org/docs/handbook/modules.html

So now rollup cannot compile the project:

D:\Project>rollup -c
Treating '@angular/platform-browser-dynamic' as external dependency
Could not resolve './app.module' from D:\Project\resources\assets\app\main.ts
Error: Could not resolve './app.module' from D:\Project\resources\assets\app\main.ts
    at c:\Programs\nodejs\global_packages\node_modules\rollup\src\Bundle.js:319:41
    at process._tickCallback (node.js:369:9)
    at Function.Module.runMain (module.js:443:11)
    at startup (node.js:139:18)
    at node.js:974:3
Type rollup --help for help, or visit https://github.com/rollup/rollup/wiki

fixExportClass.ts no longer works.

Using typescript@next I get the following:

export class A{}           // A = A;
class A{};export {A}       // ;\nexport {A};
export default class A{}   // exports["default"] = A;
class A{};export default A // export default A;

How to generate *.d.ts also?

I specified "declaration" flag true in my tsconfig.json.
But, any *d.ts files would not be generated.
I guess there is some cases want to generate *.d.ts files before bundling also when we use rollup to bundle them.

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.