How to conditionally import different files during

2019-07-05 00:37发布

问题:

Overview

I have Angular 6 app build by Angular CLI. Application is written in multiple languages. Each language has JSON file with translations of all the application texts. The filenames are ${language}.json, e.g. en.json, es.json, pl.json.

I'd like to set the language of the app during build - build the app only in one language. For that on build I need to import a single translation file, which is chosen depending on which language I'm building for.

Problem

How to conditionally import single translation file only for the language chosen during build?

In addition I'd like the translation file to be bundled together with the rest of my application's JavaScript, instead of being loaded on demand on run-time.

Sketch of a solution

const translations = import(`./translations/${lang}.json`);

Actually the above code works in Angular 6/Webpack (the only thing needed is setting compilerOptions.module: 'ESNext' in tsconfig.app.json), but not in a way that I want. Instead of resolving the import during build time and bundling the translation file together with the rest of the code, it creates a separate files (chunks) for all translations, one of which is then loaded on demand during run-time depending on the value of JavaScript lang variable.

So how do I make the import to be resolved during build-time and not run-time? Also where and how do I set lang variable during build, as I don't have access to Webpack configuration (it's hidden inside Angular CLI)

Webpack alone

When using Webpack alone, it's possible to implement this for example by using NormalModuleReplacementPlugin. But as Angular CLI hides all the Webpack configuration, I don't know how to integrate it into Angular project. Ejecting Webpack configuration from Angular CLI is the last resort for me.

回答1:

As part of the CLI 6.1 release, a feature was added that allows files to be replaced during the build other than .ts files. Previously this was used for the environment and environment.prod files

Additional files can now be set with the fileReplacements key of the angular.json configurations. As far as I know, it should work with asset files, so .json should work. It's only been added recently, but there are issues/feature details that you can look up

Let us know if it works out!

P.S. If you don't want to complicate the angular.json configuration, you could create a .js node script, and run it before doing the build, passing in the language as a param, and replacing the relevant .json file in before building the Angular bundles