AoT + Webpack + json dynamic require

时间:2017-10-12 09:48:45

标签: json angular webpack loader angular2-aot

After installing the AoT plugin (https://www.npmjs.com/package/@ngtools/webpack) for webpack, dynamic requires no longer work:

// Example that used to work
public getJson<T>(fileName: String): T {
    return require(`../../${fileName}_${this.lang}.json`);
}

With the standard ts-loader or awesome-typescript-loader etc, dynamic requires worked and webpack bundled the json files into the main app bundle. However, with the AoT/Webpack plugin the json files are not bundled at all. I don't even think the aot loader iterates over the json files anymore.

Any ideas how to get this to work again? Thanks.

Info:

https://github.com/angular/angular-cli/issues/3306

https://github.com/angular/angular-cli/pull/4153

Update:

Works somewhat with SystemJS -> System.import() but erratically https://github.com/angular/angular-cli/issues/6629#issuecomment-336411537

1 个答案:

答案 0 :(得分:2)

解决方法是使用System.import()构建加载并捆绑动态文件,然后使用标准webpack机制加载实际文件:

    public getLazyFiles<T>(somePath: string): T {
        /* AoT Hack - causes the AoT to find and prepare the dynamically loaded files */
        System.import(`../../${somePath}_${this.someSuffix}.json`);
        /* ------- */
        // This is then used by webpack to actually load the files
        return require(`../../${somePath}_${this.someSuffix}.json`);
    }

为什么需要这种解决方法在此解释:https://github.com/angular/angular-cli/issues/6629#issuecomment-336478854