Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Failed to load translation with aurelia backend and latest webpack 2.6.1 #221

Closed
Daniel-Glucksman opened this issue Jun 19, 2017 · 45 comments

Comments

@Daniel-Glucksman
Copy link

I'm submitting a bug report

Library Version:
1.6.1
Please tell us about your environment:

Operating System:
Windows 10

Node Version:
6.11.0

NPM Version:
3.10.10
Webpack
webpack 2.6.1
Browser:
Chrome 58.0.3029.110 (64-bit)
Current behavior:

I followed the aurelia docs in terms of installing the i18n aurelia plugin into a webpack project. I am using the aurelia loader backend configuration as such

.plugin(PLATFORM.moduleName('aurelia-i18n'), (instance) => {
  let aliases = ['t', 'i18n'];
  // add aliases for 't' attribute
  TCustomAttribute.configureAliases(aliases);      
  // register backend plugin
  instance.i18next.use(Backend.with(aurelia.loader));

  // adapt options to your needs (see http://i18next.com/docs/options/)
  // make sure to return the promise of the setup method, in order to guarantee proper loading
  return instance.setup({
    backend: {                                    // <-- configure backend settings
      loadPath: './locales/{{lng}}/{{ns}}.json', // <-- XHR settings for where to get the files from
    },
    attributes: aliases,
    lng : 'en',
    debug : true
  });
});

The translation file is not loaded

logger.js:24 i18next::backendConnector: loading namespace translation for language en failed failed 
loading ./locales/en/translation.json

I cannot find any sample projects or other documentation regarding this. Please help!

@dkent600
Copy link
Contributor

dkent600 commented Jun 20, 2017

I am about to attempt the same thing and have been anticipating that this could be a problem. :-(

loadPath: './locales/{{lng}}/{{ns}}.json' does nothing to tell webpack (or aurelia-webpack-plugin?) about those files.

I am guessing we're going to have to somehow manually add ./locales/**/*.json to the webpack config.

@dkent600
Copy link
Contributor

I also have worried about using aurelia.loader -- whether that is going to automatically do the webpack thing.

@zewa666
Copy link
Member

zewa666 commented Jun 20, 2017

The issue with Webpack is that it is actually just a module packer not runtime loader, aka SystemJS or RequireJS thus your translations would have to be pre-bundled and already available. To be honest I'm not that much up to date with Webpack and besides that there is currently a lot of work being invested to finalize the aurelia-webpack-plugin. So once that is stable I'll take a look at how we might integrate the bundled loader with the webpack plugin in a nicer way. @jods4 might have an idea as well on how to tackle that.

@dkent600
Copy link
Contributor

aurelia-webpack-plugin is in rc3, is quite stable and working quite well as far as I can tell. There shouldn't be a problem using the current version of it to understand what is going on with aurelia-i18next. Further, if happens to be an issue with aurelia-webpack-plugin that is contributing to this issue with aurelia-i18next, it would be really good to know about it now before the final aurelia-webpack-plugin is released, so the issue could be fixed in a timely manner.

@dkent600
Copy link
Contributor

So is the current status then that in fact aurelia-i18next doesn't work with webpack?

@jods4
Copy link

jods4 commented Jun 20, 2017

@zewa666 being a RC, aurelia-webpack-plugin is very stable. There's no API change planned at the moment, only enabling some additional scenarios. It's worth looking at right now, because it's the best time to ask for a new feature or change to support your scenario. Later will be slower, and maybe harder (once RTM, I won't be as keen to break compatibility as I might be right now).

That said, you are correct, Webpack is not a runtime loader, just a bundler. And using aurelia-loader-webpack means you can't dynamically load arbitrary content from aurelia-loader, which is what Backend.with(aurelia.loader) does, right?

One option would be to use another backend, one that is able to dynamically load any file from your server.

Another option is to ensure that webpack knows of all the possible values at compile-time (which is not always possible). This doesn't mean you put everything in the same file, you can for example create one chunk for each culture.

I am sure there are many ways to go about that, here's the most naive one:

// In your webpack config
plugins: [
  new ModuleDependenciesPlugin({
    "aurelia-i18n": [ 
      { name: "locales/en/translations.json", chunk: "lang-en" },
      { name: "locales/en/additional.json", chunk: "lang-en" },
      { name: "locales/fr/translations.json", chunk: "lang-fr" },
    ]
  }
]

It looks tedious that way, but remember this is all JS, so you could write a function to produce that array of dependencies from files on disk, or even better your own plugin on top of ModuleDependenciesPlugin!

With the config above, using aurelia-loader to load, say locales/en/tranlsations.json should work, and each language pack gets its own file that is lazily loaded (thanks to chunk property).

Important notice: the ability to use chunk in ModuleDependenciesPlugin was added to RC3. The config above would put everything in the same bundle as aurelia-i18n when used with RC2.
RC3 is not published yet, it's available from the branch on github but needs to be built (npm run build).

@dkent600
Copy link
Contributor

I find that the Backend.with(aurelia.loader) does appear to be resolving to the WebpackLoader.

@dkent600
Copy link
Contributor

Ooops, sorry, I guess I saw the rc3 on the GitHub page, didn't realize it wasn't released yet.

@jods4
Copy link

jods4 commented Jun 20, 2017

If you build with Webpack, of course it does -- at least by default.

When building with Webpack, Aurelia is automatically configured to use WebpackLoader from aurelia-loader-webpack as its internal "loader".

There is an option to use your own custom loader instead, if you are hardcore. If you use Webpack, I think it would derive from (or compose) WebpackLoader.

That said, if the problem is only i18n, it's much simpler to use a different Backend than a custom aurelia-loader.

@jods4
Copy link

jods4 commented Jun 20, 2017

Feel free to use RC3 from Github. It's feature complete and tested.
The last thing I want to do before releasing the code is ensure compatibility with upcoming Webpack 3.

@dkent600
Copy link
Contributor

@zewa666

OK, I just tried the workaround offered by @jods4 (using ModuleDependenciesPlugin) and find that it does enable the code to find the translation.json files. However, it fails to "parse" them. It appears to expect these files to be returned as text, when in fact they are being returned as already-parsed objects.

@dkent600
Copy link
Contributor

@zewa666 @jods4 Further to ^^^, I changed the json loader as follows:

{ test: /\.json$/i, use: 'raw-loader' }

And now it completely works. I do have a question how I could scope this raw loader spec to i18n, as I worry that it might break other cases where json is being loaded in the default manner.

@dkent600
Copy link
Contributor

dkent600 commented Jun 20, 2017

@jods4 My only remaining issue: I am using aurelia-i18n in a library, and do not want the application to have to be responsible for manually setting these dependencies for my library. Do you kindly have any suggestions, thanks?

@zewa666
Copy link
Member

zewa666 commented Jun 20, 2017

@dkent600 I'm aware of the method to upfront bundle your translations, as stated in my reply. The problem with this though is that I don't think that this really solves the issue as, like you found out yourself, you just delegate the problem to the consumer and have him do the settings correctly. This is not the quality level that Require and SystemJS do offer, it's more comparable to prebundling translations with those. Like @jods4 mentioned in the meantime it would be recommended to use an alternative loader like xhr which is mentioned in the docs.

I'm sure though that we can find an alternative for webpack as well. One idea would be to provide a gulp task, which can also be used with the CLI to help you do the translation bundling through a simple wizard. The reason why I'm holding off to start any work here is exactly the CLI supporting webpack (in the works) as it would tremendously simplify such configuration tasks.
Another option would be to include the basic xhr parts into the i18n loader.

@jods4
Copy link

jods4 commented Jun 20, 2017

@dkent600 an easy way to restrict that loader is to use a more specific condition. For example you can add include: "path/to/translations/folder". Docs

@zewa666

One idea would be to provide a gulp task, which can also be used with the CLI to help you do the translation bundling through a simple wizard. The reason why I'm holding off to start any work here is exactly the CLI supporting webpack (in the works) as it would tremendously simplify such configuration tasks.

Please don't go CLI-first or introduce Gulp.

  • Using Gulp with Webpack doesn't make much sense, except to ease migration.
  • There are people (myself included) who don't use the CLI and we have to provide a good experience without.

We should first provide a good webpack-only experience, then build additional tools on top of it. Not the other way round.

As I suggested above, it would not be too hard to create a Localization plugin that works like this:

plugins: [
  new AureliaPlugin(),
  new LocalizationPackerPlugin({
    files: "locales/{lang}/**/*.json",
    chunk: "lang-{lang}",
  }),
]

@zewa666
Copy link
Member

zewa666 commented Jun 21, 2017

@jods4 We definitely can and should do that plugin as it would further simplify the configuration.. But still this doesn't feel like a good experience in my opinion. You still end up with having the end user to define custom configurations. Whatever is the solution, it shouldn't be solely based on bundles or we'll never reach the UX provided by SystemJS or RequireJS, where the consumer essentially has to do nothing. Reading @dkent600 's last comment you can see that there is definitely a use case for a no-configuration option

I'm not favoring any solution over the other, but since the CLI is our proposed way to go, we definitely want to have good tooling and simplify as much as possible with it. Prioritization wise you're right that it would make sense to first contribute to said packer plugin and then build the CLI tooling upon that.

So bottom line, bundling plugin is good, but thats essentially just syntax sugar for what you can achieve now with a narrowed down json loader. The real task is to find something which provides a no-configuration option as a fallback. So far having baked in XHR fallback feels like a viable solution. I hope we can come up with more ideas on that.

Regarding the plugin, I'd be happy if you could provide some guidance on how to create that.

@jods4
Copy link

jods4 commented Jun 21, 2017

As far as no config goes then using a different backend (e.g. XHR) is the only solution I see.

@dkent600
Copy link
Contributor

dkent600 commented Jun 21, 2017

Just for the record, I don't use the Aurelia CLI and at the moment have no need for it. I understand how to use npm and am learning how to use webpack. The dotnet CLI tool and associated project templates work great for me so far, better in fact than what the Aurelia CLI creates, which for my taste creates a lot of bloat, and last I tried, didn't do webpack. The only thing I'm aware of that the Aurelia CLI does that the dotnet CLI doesn't is set up a JavaScript/browser test project.

I totally agree with the proposition that this issue with Webpack be addressed at a more fundamental level than the Aurelia CLI, to the extent possible.

@dkent600
Copy link
Contributor

dkent600 commented Jun 21, 2017

@zewa666 With respect to your comment

I think it might be acceptable for my use case to, instead of modifying the webpack.config.js file (with new LocalizationPackerPlugin as suggested by @jods4), rather, supply a new backend loader with the aurelia-i18n configuration, something like this:

import Backend from 'i18next-webpack-backend'
instance.i18next.use(Backend);

Would this make sense?

Hopefully this loader could also be configurable in the webpack.config.js, to define chunks, for example.

@zewa666
Copy link
Member

zewa666 commented Jun 21, 2017

@dkent600 what you're proposing there is exactly what i18next-xhr-backend is doing. Take a look at the docs below the custom bundled loader. It will essentially just use XHR calls to request your translations files, without the need of having to pre-bundle files.

I wouldn't like to introduce yet another loader as that beats the purpose of having a unified aurelia i18n loader and just for the sake of one bundling tool provide another option. Instead I could see that the current aurelia loader also leverages XHR as fallback for webpack, if the files aren't bundled.
To achieve that the best thing would be to define a fallback backend, which can be used if the aurelia i18n loader is not able to find a suitable file

@dkent600
Copy link
Contributor

dkent600 commented Jun 21, 2017

@zewa666 Yes, the fact that what I proposed is the same mechanism as with the XHR loader is one reason why I thought it would be a good pattern to follow. I can see, though, that it doesn't really make sense.

Making the current loader fall back to XHR seems reasonable.

However, in my use case, I would like to have a way by which my plugin can cause its translation.json files to be automatically bundled so that XHR would not be needed, using import or something (@jods4 ?).

@dkent600
Copy link
Contributor

dkent600 commented Jun 21, 2017

@zewa666

OK, I tested this using the XHR backend loader and there is an issue. Recalling that my code is in a plugin library that is installed via npm, the translation.json files are therefore buried under node_modules, outside of where XHR loader will ever be able to find them.

Thus it seems necessary to either bundle the translation files, or copy them into the dist folder. The latter is not acceptable due to its burden on the application.

This reinforces my request in the comment above ^^^ to have "a way by which my plugin can cause its translation.json files to be automatically bundled [...] using import or something" with the rest of the required plugin files, and in such a way that the i18n backend loader will be able to find them and use them without using XHR.

It seems to me like this is fundamental to webpack, with perhaps some help from Aurelia, and is perhaps readily accomplished, I just have to figure out how to do it. But I'm guess that these files will be scoped to my plugin and not the i18n plugin, and thus the i18n plugin will never be able to find them. @jods4 ?

@jods4
Copy link

jods4 commented Jun 21, 2017

However, in my use case, I would like to have a way by which my plugin can cause its translation.json files to be automatically bundled so that XHR would not be needed, using import or something

PLATFORM.moduleName is your friend.

That said, as a library, you still rely on the end-user using the aurelia-loader backend, as opposed to, say, XHR :)

@dkent600
Copy link
Contributor

@jods4 Wow, adding this line in the plugin config:

PLATFORM.moduleName("./locales/en-CA/translation.json");

causes the default aurelia-i18n backend loader to be able to find it, with the caveat: I have to add the following to the webpack.config.vendor.js:

{ test: /\.json$/i, use: 'raw-loader' }

And just for the record, the loadPath is set as:

loadPath: 'ferngully-aurelia-tools/locales/{{lng}}/{{ns}}.json'

(Note the path starts with the name of my plugin and does not include the "dist" or module type parts of the path.)

Indeed as you have noted and I have found, the XHR loader will not ever work in my use case, but I'm not sure that is a problem for me, or at least, I'll cross that bridge if I ever come to it.

So would I be correct in stating that no further changes are needed with respect to this issue? @zewa666 (Note I am not the person who originally created this issue.)

@dkent600
Copy link
Contributor

@zewa666 There is an improvement that could be made here:

Note from above that the application has to add { test: /\.json$/i, use: 'raw-loader' } to the webpack.config.json.

The only reason I have to do this is because Aurelia-i18n assumes that the loaded JSON is a string that must be parsed. If instead it made a simple check for whether the json has already been parsed and is in fact already an object, then the application would not be required to add the raw-loader, and my use case would therefore require no change to the webpack.config.json.

Would you be willing to make this change?

@zewa666
Copy link
Member

zewa666 commented Jun 21, 2017

sounds good. Regarding your parsing problem, if you take a look at the loader here https://github.com/aurelia/i18n/blob/master/src/aurelia-i18n-loader.js#L58 you'll find the parser being executed, which indeed just leverages the default JSON.parse mechanism. So adding a check of type object should fix it. I'll happily accept PRs for that as I can't get to it for the next few days.

@dkent600
Copy link
Contributor

@zewa666 Forgive me for spamming this issue, but in trying to make this code change, I find that the unit tests are failing:

Chrome 58.0.3029 (Windows 10 0.0.0) testing aurelia configure routine should accept a setup callback passing back the instance FAILED
TypeError: frameworkConfig.postTask is not a function
at registerI18N (src/aurelia-i18n.js:44:19)
at configure (src/aurelia-i18n.js:100:26)
at Object.eval (test/unit/aurelia.integration.spec.js:28:32)
Chrome 58.0.3029 (Windows 10 0.0.0): Executed 80 of 83 (1 FAILED) (skipped 3) (0.247 secs / 0.228 secs)

@dkent600
Copy link
Contributor

Here is the PR: #225

GitHub believes that all tests passed. But for what it's worth, they don't for me on my machine.

@zewa666
Copy link
Member

zewa666 commented Jun 21, 2017

yeah strange although it worked on my machine. Anyways thanks for the contribution and I'm happy we got a initial solution for this. I'll close this meanwhile but I'm sure there will be more in future to follow this

@zewa666 zewa666 closed this as completed Jun 21, 2017
@dkent600
Copy link
Contributor

Thanks for everyone's help! @zewa666 @jods4

@Dresel
Copy link

Dresel commented Oct 2, 2017

Sorry to reactivate this discussion, but I'm having a hard time to get this settled.

I have added

new ModuleDependenciesPlugin({
    "aurelia-i18n": [
        { name: path.join(__dirname, "/locales/en/translation.json") },
        { name: path.join(__dirname, "/locales/de/translation.json") }
    ]
}),

to my plugins definition of my webpack.config.vendor.js. I had to use __dirname because otherwise webpack looks in the node_modules folder instead of the project root folder.

But I'm still getting the

i18next::backendConnector: loading namespace translation for language de failed failed loading

I'm using the default i18n configuration:

.plugin(PLATFORM.moduleName('aurelia-i18n'), (instance) => {
    let aliases = ['t', 'i18n'];
    // add aliases for 't' attribute
    TCustomAttribute.configureAliases(aliases);
    // register backend plugin
    instance.i18next.use(Backend.with(aurelia.loader));
    // adapt options to your needs (see http://i18next.com/docs/options/)
    // make sure to return the promise of the setup method, in order to guarantee proper loading

    return instance.setup({
        backend: {
            loadPath: './locales/{{lng}}/{{ns}}.json'
        },
        attributes: aliases,
        lng: 'de',
        fallbackLng: 'en',
        debug: true
    });
});

I would really appreciate if someone can give me a hint on how to get this working.

@jcarruo
Copy link

jcarruo commented Oct 7, 2017

I send @Dresel, I've read this over several times yet i can get any translations going with the aurelia typescript webpack nav skeleton. Is a sample around document full config of webpack with aurelia i18n?

@bellstrand
Copy link

@Dresel I had on the same problem as you, and my issue was that I was not allowed to place my "locales" folder outside of the src folder when using this "fix". But after moving it in and fixing the paths it worked great!

main.js

loadPath: 'locales/{{lng}}/{{ns}}.json'

webpack.config.js

new ModuleDependenciesPlugin({
    "aurelia-i18n": [
        { name: 'locales/en/translation.json', chunk: 'lang-en' },
        { name: 'locales/sv/translation.json', chunk: 'lang-sv' }
    ]
})

@jcarruo
Copy link

jcarruo commented Oct 7, 2017

Ok great tip! Will give this a try and see how i end up. Cheers

@jcarruo
Copy link

jcarruo commented Oct 7, 2017

so. i've battled with this for nights. and I was literally typing up a detailed description of my config and stepping through each part with build, test etc. then it started bloody working. it was almost more infuriating then when i just didn't work!!! lol

so I've obviously made a rookie error somewhere along the way which was corrected when I stepped through it bit by bit. thanks for the info guys!

@zewa666
Copy link
Member

zewa666 commented Oct 8, 2017

@Dresel glad you got it. Now since the necessary steps to get it running are so fresh on your mind, would you bother to write down some docs so others can benefit of your hard work?

@loicndjoyi
Copy link

Hello,
I'm also having a hard time to get this settled.

Main.js
image

webpack.conf.js
image

But I'm still getting the i18next::backendConnector: loading namespace translation for language en failed failed loading

Node Version:
6.11.0
NPM Version:
5.6.0
Webpack
webpack 3.10.0

@bellstrand
Copy link

@Lloyc How does your folder structure look? (the locales folder should be located inside the src folder with that setup).
It would also be easier for us if you posted a bit more from your configs (the whole loader config and which loader you are using etc).

@loicndjoyi
Copy link

Thank you @bellstrand for the quick reply.

Here is my webpack.conf

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const project = require('./aurelia_project/aurelia.json');
const { AureliaPlugin, ModuleDependenciesPlugin } = require('aurelia-webpack-plugin');
const { optimize: { CommonsChunkPlugin, UglifyJsPlugin }, ProvidePlugin } = require('webpack');
const { TsConfigPathsPlugin, CheckerPlugin } = require('awesome-typescript-loader');


// config helpers:
const ensureArray = (config) => config && (Array.isArray(config) ? config : [config]) || [];
const when = (condition, config, negativeConfig) =>
  condition ? ensureArray(config) : ensureArray(negativeConfig);

// primary config:
const title = 'Aurelia Navigation Skeleton';
const outDir = path.resolve(__dirname, project.platform.output);
const srcDir = path.resolve(__dirname, 'src');
const nodeModulesDir = path.resolve(__dirname, 'node_modules');
const baseUrl = '/';

const cssRules = [
  { loader: 'css-loader' },
];

module.exports = ({ production, server, extractCss, coverage, language } = {}) => ({
  resolve: {
    extensions: ['.ts', '.js'],
    modules: [srcDir, 'node_modules'],
  },
  entry: {
    app: ['aurelia-bootstrapper'],
    vendor: ['bluebird'],
  },
  output: {
    path: outDir,
    publicPath: baseUrl,
    filename: production ? '[name].[chunkhash].bundle.js' : '[name].[hash].bundle.js',
    sourceMapFilename: production ? '[name].[chunkhash].bundle.map' : '[name].[hash].bundle.map',
    chunkFilename: production ? '[name].[chunkhash].chunk.js' : '[name].[hash].chunk.js'
  },
  devServer: {
    contentBase: outDir,
    // serve index.html for all 404 (required for push-state)
    historyApiFallback: true
  },
  devtool: production ? 'nosources-source-map' : 'cheap-module-eval-source-map',
  module: {
    rules: [
      // CSS required in JS/TS files should use the style-loader that auto-injects it into the website
      // only when the issuer is a .js/.ts file, so the loaders are not applied inside html templates
      {
        test: /\.css$/i,
        issuer: [{ not: [{ test: /\.html$/i }] }],
        use: extractCss ? ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: cssRules
        }) : ['style-loader', ...cssRules],
      },
      {
        test: /\.css$/i,
        issuer: [{ test: /\.html$/i }],
        // CSS required in templates cannot be extracted safely
        // because Aurelia would try to require it again in runtime
        use: cssRules
      },
      { test: /\.html$/i, loader: 'html-loader' },
      { test: /\.ts$/i, loader: 'awesome-typescript-loader', exclude: nodeModulesDir },
      { test: /\.json$/i, loader: 'raw-loader' },
      // use Bluebird as the global Promise implementation:
      { test: /[\/\\]node_modules[\/\\]bluebird[\/\\].+\.js$/, loader: 'expose-loader?Promise' },
      // embed small images and fonts as Data Urls and larger ones as files:
      { test: /\.(png|gif|jpg|cur)$/i, loader: 'url-loader', options: { limit: 8192 } },
      { test: /\.woff2(\?v=[0-9]\.[0-9]\.[0-9])?$/i, loader: 'url-loader', options: { limit: 10000, mimetype: 'application/font-woff2' } },
      { test: /\.woff(\?v=[0-9]\.[0-9]\.[0-9])?$/i, loader: 'url-loader', options: { limit: 10000, mimetype: 'application/font-woff' } },
      // load these fonts normally, as files:
      { test: /\.(ttf|eot|svg|otf)(\?v=[0-9]\.[0-9]\.[0-9])?$/i, loader: 'file-loader' },
      ...when(coverage, {
        test: /\.[jt]s$/i, loader: 'istanbul-instrumenter-loader',
        include: srcDir, exclude: [/\.{spec,test}\.[jt]s$/i],
        enforce: 'post', options: { esModules: true },
      })
    ]
  },
  plugins: [
    new AureliaPlugin(),
    new ProvidePlugin({
      'Promise': 'bluebird'
    }),
    new ModuleDependenciesPlugin({
      'aurelia-testing': ['./compile-spy', './view-spy'],
      "aurelia-i18n": [
        { name: 'locales/en-CA/translation.json', chunk: 'en-CA' },
        { name: 'locales/en-US/translation.json', chunk: 'en-US' },
        { name: 'locales/fr-CA/translation.json', chunk: 'fr-CA' }
    ]
    }),
    new TsConfigPathsPlugin(),
    new CheckerPlugin(),
    new HtmlWebpackPlugin({
      template: 'index.ejs',
      minify: production ? {
        removeComments: true,
        collapseWhitespace: true,
        collapseInlineTagWhitespace: true,
        collapseBooleanAttributes: true,
        removeAttributeQuotes: true,
        minifyCSS: true,
        minifyJS: true,
        removeScriptTypeAttributes: true,
        removeStyleLinkTypeAttributes: true,
        ignoreCustomFragments: [/\${.*?}/g]
      } : undefined,
      metadata: {
        // available in index.ejs //
        title, server, baseUrl
      }
    }),
    ...when(extractCss, new ExtractTextPlugin({
      filename: production ? '[contenthash].css' : '[id].css',
      allChunks: true
    })),
    ...when(production, new CommonsChunkPlugin({
      name: ['common']
    })),
    ...when(production, new CopyWebpackPlugin([
      { from: 'static/favicon.ico', to: 'favicon.ico' }
    ])),
    ...when(production, new UglifyJsPlugin({
      sourceMap: true
    }))
  ]
});

Here is my folder structure:
image

@bellstrand
Copy link

@Lloyc Sorry for not being clear... I meant the config you had in your main.js file.
And the loader that you are trying to use in main.js (aurelia-i18n or i18next-xhr-backend)?

@loicndjoyi
Copy link

Thank you for the clarification @bellstrand. The loader i'm trying to use is aurelia-i18n.

Here is my main.ts

/// <reference types="aurelia-loader-webpack/src/webpack-hot-interface"/>
// we want font-awesome to load as soon as possible to show the fa-spinner
import { Aurelia } from "aurelia-framework";
import { TCustomAttribute } from "aurelia-i18n";
import { PLATFORM } from "aurelia-pal";
import * as Bluebird from "bluebird";
import Backend from "i18next-xhr-backend";
import environment from "./environment";

// remove out if you don't want a Promise polyfill (remove also from webpack.config.js)
Bluebird.config({ warnings: { wForgottenReturn: false } });

export function configure(aurelia: Aurelia) {
    aurelia.use
        .standardConfiguration()
        .plugin(PLATFORM.moduleName("aurelia-i18n"), (instance) => {
            const aliases = ["t", "i18n"];
            // add aliases for 't' attribute
            TCustomAttribute.configureAliases(aliases);

            // register backend plugin
            instance.i18next.use(Backend);

            // adapt options to your needs (see http://i18next.com/docs/options/)
            // make sure to return the promise of the setup method, in order to guarantee proper loading
            return instance.setup({
                backend: {                                  // <-- configure backend settings
                    loadPath: "locales/{{lng}}/{{ns}}.json", // <-- XHR settings for where to get the files from
                },
                attributes: aliases,
                lng: "en-CA",
                fallbackLng: "en-US",
                debug: true,
            });
        })
        .feature(PLATFORM.moduleName("resources/index"));

    // Uncomment the line below to enable animation.
    // aurelia.use.plugin(PLATFORM.moduleName('aurelia-animator-css'));
    // if the css animator is enabled, add swap-order="after" to all router-view elements

    // Anyone wanting to use HTMLImports to load views, will need to install the following plugin.
    // aurelia.use.plugin(PLATFORM.moduleName('aurelia-html-import-template-loader'));

    if (environment.debug) {
        aurelia.use.developmentLogging();
    }

    if (environment.testing) {
        aurelia.use.plugin(PLATFORM.moduleName("aurelia-testing"));
    }

    aurelia.start().then(() => aurelia.setRoot(PLATFORM.moduleName("app")));
}

@bellstrand
Copy link

bellstrand commented Jan 17, 2018

Okay great! Think I got the problem! :)
Right now your config is using i18next-xhr-backend and not aurelia-i18n's backend.
Change:

instance.i18next.use(Backend);

To:

instance.i18next.use(Backend.with(aurelia.loader));

And:

import { TCustomAttribute } from "aurelia-i18n";

To:

import {Backend, TCustomAttribute} from 'aurelia-i18n';

And then you can remove "import Backend from "i18next-xhr-backend";"

@loicndjoyi
Copy link

Thank you so much @bellstrand ! It works!

@rezabojnordi
Copy link

eeror-38

error using sudo npm start build

@rezabojnordi
Copy link

rezabojnordi commented Feb 4, 2018

Error building - when new library is added?????

help me plz

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

9 participants