0

I've a simple custom component called DatepickerComponent. This is the project structure.

enter image description here

I've a simple JS file calendarLanguages.js and it is under the same roof. Here is the code.

calendarLanguages.js

export const spanish = {
  dayNames: ['domingo', 'lunes', 'martes', 'miércoles', 'jueves', 'viernes', 'sábado'],
  monthNames: ['enero', 'febrero', 'marzo', 'abril', 'mayo', 'junio', ...],
  monthNamesShort: ['ene', 'feb', 'mar', 'abr', 'may', 'jun', ...]
};

In my datepicker.component.ts file I'm importing it as:

import { Component, OnInit } from '@angular/core';
import * as localeLanguage from './calendarLanguages.js';
// import * as localeLanguage from './calendarLanguages'; <--- also tried

@Component({
  ...
})
export class DatepickerComponent implements OnInit {

  ...
  selectedLanguage: any={};

  constructor() { }

  ngOnInit() {
    this.selectedLanguage=localeLanguage.spanish;
  }
}

I'm simply building the project with ng build. But I'm getting this error:

BUILD ERROR Could not resolve './calendarLanguages' from dist\pinc-insights-base-lib\esm2015\lib\datepicker\datepicker.component.js Error: Could not resolve './calendarLanguages' from dist\pinc-insights-base-lib\esm2015\lib\datepicker\datepicker.component.js at error (C:\Users\320050772\Documents\pinc-insights-base\node_modules\rollup\dist\rollup.js:3460:30) at C:\Users\320050772\Documents\pinc-insights-base\node_modules\rollup\dist\rollup.js:21854:25

Please help me.

Tanzeel
  • 4,174
  • 13
  • 57
  • 110

1 Answers1

2

You should declare the calendarLanguages.js file in the angular.json like below

"scripts": [
  "src/calendarLanguages.js"
]

This will add the js File and its content in global context. After that declare variable out side your component class like this (Name should be same as in js file) :

declare const spanish: any;

@Component({
  ...
})

After this you will be able to access the value at runtime like this

this.selectedLanguage= spanish;
sarfrazanwar
  • 373
  • 5
  • 16
  • In this case, where do i keep my `calendarLanguages.js` file. I mean in which directory. – Tanzeel Feb 01 '21 at 07:52
  • 1
    You can place it anywhere and just provide the path. As a good practice, you should use a structure like this "src/assets/js/calendarLanguages.js" to store js files. You can create a directory if not present already. – sarfrazanwar Feb 01 '21 at 07:57
  • things are working as expected. let me show this to my tech lead, run some test cases. I'll get back to you. thanks – Tanzeel Feb 01 '21 at 08:25
  • It this works fine , You can accept the answer. Thanks – sarfrazanwar Feb 01 '21 at 18:14
  • From here we can make changes but yes, for now, i got my answer :-) – Tanzeel Feb 02 '21 at 03:38
  • Hi Sarfarz. Can we have an offline discussion please. It's not working in the actual scenario. Need help plz. – Tanzeel Feb 02 '21 at 08:29