Webpack raw-loader not working after Angular update

1.8k Views Asked by At

I have recently updated my Angular application to V12. I am using Angular's own Internationalization library @angular/localize. I am using webpack's raw-loader to load the xlf translation files as a string in my main.ts using the following code

const locale = document['locale'] as string;
const translations =   require(`raw-loader!./assets/locale/messages.${locale}.xlf`).default;

platformBrowserDynamic().bootstrapModule(AppModule, {
providers: [
{ provide: TRANSLATIONS, useValue: translations },
{ provide: LOCALE_ID, useValue: locale },
{ provide: TRANSLATIONS_FORMAT, useValue: 'xlf' }
 ]
});

After the update I get the following error Error: Module not found: Error: Can't resolve 'raw-loader'

What could be the reason for this? Is there any way other than raw-loader?

2

There are 2 best solutions below

0
On

I had that issue migrating the angular version ,and i've solved it installing it with npm install raw-loader --save-dev . It is because angular 12 now uses webpack5. If you don't solve the problem try to change const translations = require(raw-loader!./assets/locale/messages.${locale}.xlf).default; to an ES import dynamic declaration like in your case that you use a variable ${locale} inside it, maybe you can take a look at this post ES6 variable import name in node.js? . and use !!raw-loader... instead of raw-loader

0
On

Since webpack version 5 the use of loaders like the raw-loader is deprecated and replaced with a concept called Asset Modules.

For this to work you first need to define how assets should be loaded. This is done in the webpack's config. A replacement for the raw-loader is the asset/source type:

webpack.config.js

module.exports = {
  ...
  module: {
    rules: [
      {
       test: /\.xlf/,
       type: 'asset/source',
      }
    ]
  },
};

After that you can just import your asset files like any other local dependency:

main.ts

const translations = require(`./assets/locale/messages.${locale}.xlf`).default;