我需要做类似的事情:
if (condition) {
import something from 'something';
}
// ...
if (something) {
something.doStuff();
}
Run Code Online (Sandbox Code Playgroud)
上面的代码没有编译; 它抛出SyntaxError: ... 'import' and 'export' may only appear at the top level.
我试着用System.import如图所示这里,但我不知道在哪里System的来了.是不是最终被接受的ES6提案?该文章中"programmatic API"的链接将我转储到已弃用的文档页面.
有没有办法根据angular-cli@1.0.0-beta.16中的环境变量有条件地更改导入?我试图以一种不需要在客户端代码中导入服务的代码更改的方式来实现它,但是在需要时我可以指定一个构建标志来交换模拟服务.
我试过在这篇文章中使用了一种模式:
文件结构:
Run Code Online (Sandbox Code Playgroud)MyService MyServiceMock.ts MyServiceReal.ts index.ts在index.ts中,您可以拥有以下内容:
Run Code Online (Sandbox Code Playgroud)import { environment} from '../environments/environment'; export const MyService = environment.mock ? require('./MyServiceMock').MyServiceMock: require('./MyServiceReal').MyServiceReal;在您的客户端代码中,导入MyService:
Run Code Online (Sandbox Code Playgroud)import MyService from './myservice/index';
页面加载,我可以看到在单步执行代码时注入依赖项,但是编译错误(我认为是TypeScript错误)沿着这一行Cannot find name 'MyService'.
我需要根据浏览器平台动态导入库。防止 Angular Universal 因为使用 window 对象而给出错误。
import * as Muuri from 'muuri';
Run Code Online (Sandbox Code Playgroud)
所以我想要的是这样的:
if (isPlatformBrowser(this.platform)) {
import * as Muuri from 'muuri';
}
else {
declare var Muuri;
}
Run Code Online (Sandbox Code Playgroud)
显然这是行不通的。