简体   繁体   English

角度改变模块从es6到commonJs的结果

[英]Angular change module from es6 to commonJs consequence

I tried to import FileSaver for my app. 我尝试为我的应用导入FileSaver 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 定位ECMAScript 2015模块时,无法使用导入分配

I followed the solution by changing the module inside tsconfig.json from es6 to commonjs. 我通过将tsconfig.json中的模块从es6更改为commonjs来跟踪解决方案。

It all works fine now. 现在一切正常。 However, I am abit worried about what is the consequence for changing from es6 to commonjs. 但是,我很担心从es6变为commonjs的后果是什么。 Obviously it was es6 for a reason right? 显然是es6是有原因的吗?

Is there a way to do it such that I dont have to change? 有没有办法做到这一点,我不必改变?

Yes, if you are using TypeScript, use es6/TypeScript module loading syntax: 是的,如果您使用的是TypeScript,请使用es6 / TypeScript模块加载语法:

import { type } from './module';

When you compile TypeScript to JavaScript, you can target any module loader you want: 将TypeScript编译为JavaScript时,可以定位所需的任何模块加载器:

es6
system
commonjs
AMD
UMD

You can target the module system from tsconfig.json: 您可以从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 (ie node_modules/systemjs/dist/system.js) 例如,如果您定位“system”或“commonjs”,请确保包含兼容的脚本以正确加载模块(即node_modules / systemjs / dist / system.js)

My Advice, if you are writing your ng2 app in TypeScript 我的建议,如果您在TypeScript中编写ng2应用程序

IMHO, es6 provides the cleanest module loading syntax. 恕我直言,es6提供了最干净的模块加载语法。 I prefer writing Angular2 programs with TypeScript and using es6 language features (including the cleaner module loading syntax). 我更喜欢使用TypeScript编写Angular2程序并使用es6语言功能(包括清理器模块加载语法)。 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). 在将TypeScript编译为JavaScript时,我尝试以es5为目标,因为如今大多数浏览器都提供接近100%的合规性而没有垫片,并使用systemjs作为模块加载器(如果我想稍后更改格式,则最灵活)。

In the FileServer code, write it in TypeScript, and use es6 module loading syntax. 在FileServer代码中,使用TypeScript编写它,并使用es6模块加载语法。 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. 这样,它将被编译为您要定位的模块加载器语法,这应该与其余的ts文件保持一致。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM