3

I tried to import FileSaver for my app. And the only way that I got it to work was through the the following command

import filesaver = require('filesaver');

Then I get this error

Import assignment cannot be used when targeting ECMAScript 2015 modules

I followed the solution by changing the module inside tsconfig.json from es6 to commonjs.

It all works fine now. However, I am abit worried about what is the consequence for changing from es6 to commonjs. Obviously it was es6 for a reason right?

Is there a way to do it such that I dont have to change?

1
  • the equivalent es6 line would be import * as filesaver from 'filesaver'; Commented Feb 12, 2017 at 23:27

1 Answer 1

4

Yes, if you are using TypeScript, use es6/TypeScript module loading syntax:

import { type } from './module';

When you compile TypeScript to JavaScript, you can target any module loader you want:

es6
system
commonjs
AMD
UMD

You can target the module system from tsconfig.json:

"compilerOptions": {
  ...
  "module": "commonjs",
}

Browsers don't yet natively support module loading. Until they do, include the necessary script depending on which module system you use.

For example, if you target "system" or "commonjs", then make sure you include a compatible script to load the module correctly (i.e. node_modules/systemjs/dist/system.js)

My Advice, if you are writing your ng2 app in TypeScript

IMHO, es6 provides the cleanest module loading syntax. I prefer writing Angular2 programs with TypeScript and using es6 language features (including the cleaner module loading syntax). When it comes to compiling TypeScript to JavaScript, I try to target es5, as most browsers today provide close to 100% compliance without a shim, and use systemjs as the module loader (most flexible if I want to change formats later on).

In the FileServer code, write it in TypeScript, and use es6 module loading syntax. That way, it will be compiled to the module loader syntax that you are targeting, which should be consistent with the rest of your ts files.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.