Encountering an "Unexpected token" error when importing a JSON file in TypeScript even though the JSON is valid

I recently read an article on Hacker Noon about importing JSON into TypeScript, and decided to give it a try in my code. Here's the import line I used:

import data from './assets/fonts/helvetiker_bold.typeface.json';

To test if the import was working, I included a simple font JSON file:

{"hi":"true"}

Additionally, I checked my tsconfig.json file to ensure all necessary options were set:

{
  "compilerOptions": {
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "esModuleInterop": true,
    "target": "es5",
    "module":"es2015",
    "lib": ["es2015", "es2016", "es2017", "dom"],
    "strict": true,
    "sourceMap": true,
    "declaration": true,
    "allowSyntheticDefaultImports": true,
    "experimentalDecorators": true,
    "emitDecoratorMetadata": true,
    "declarationDir": "dist/types",
    "outDir": "dist/lib",
    "typeRoots": [
      "node_modules/@types"
    ]
  },
  "include": [
    "src"
  ]
}

Despite all this, I encountered an error during compilation:

[!] Error: Unexpected token
src\assets\fonts\helvetiker_bold.typeface.json (1:5)
1: {"hi":"true"}
        ^

I'm unsure what the issue is, so any assistance would be greatly appreciated.

Answer №1

To tackle the issue at hand, I devised a strategy of creating a specialized class that encapsulated my JSON object and leveraged it in conjunction with the FontLoader.parse() function instead of fetching the JSON data from an external file. Here's how it was executed:

  1. Established a new file named HelvetikerUtils.ts to house my JSON object:
export class HelvetikerUtil {
    constructor() { }

    data: any = <YOUR_FONT_JSON_HERE>
}
  1. Referenced this class as needed

import { HelvetikerUtil } from './HelvetikerUtil';

  1. Utilized FontLoader.parse() for data loading
let myFont = new HelvetikerUtil;
let FONTLoader = new FontLoader();
let font = FONTLoader.parse(myFont.data);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Determining the output type by considering the presence of optional parameters

function customFunction<T>(defaultValue?: T) { return defaultValue; } const definitelyNullOrUndefined = customFunction<string>(); // type: string | undefined const definitelyStringType = customFunction<string>('foobar'); // ...

Navigating through an Angular 2 service

I'm struggling to retrieve an array from a JSON API and then loop through it. I can't seem to grasp how it all fits together. Any guidance would be greatly appreciated. This is what my service looks like: import {Injectable} from '@angular ...

What exactly does the dollar sign signify in plain JavaScript code?

While watching a tutorial on object literals in JavaScript, I noticed something interesting. The instructor demonstrated creating an object like this: var Facebook = { name: 'Facebook', ceo: { firstName: "Mark", favColor: ...

Display JSON data values using jQuery

After receiving my data from Json, I am having trouble displaying it. Below is the javascript code snippet: jQuery( document ).ready( function( $ ) { $('select[name="country_id"]').on('change', function() { $.ajaxSetup({ ...

Working with nested lists in C# JSON to return data in a hierarchical structure

public class Entry { public string playerOrTeamId { get; set; } public string playerOrTeamName { get; set; } public string division { get; set; } public int leaguePoints { get; set; } public int wins { get; set; } public int losses ...

Creating a table dynamically using JSON data can be easily achieved with a jQuery function

Is there a way to extract a JSON object from a local file and present it in a table using jQuery? Take a look at the JSON file content below (jsondata.json): { "scores" : [ ["3/1/2011", 610],["4/1/2011", 610],["5/1/2011", 610],["6/1/2011", 610], ["7/1/2 ...

What is the reasoning behind exporting it in this manner in the index file?

As I was going through a tutorial about nests, there was this step where the instructor made a folder named "dtos" and inside it, they created two dto files (create-user.dto and edit-user.dto). Following that, they also added an index file in the same fold ...

What is the best way to structure this information in Swift for easy understanding by the backend system?

I've been working on formatting my data to make it readable for the backend, but I can't seem to figure out what's missing. Here is the desired data format: { "month": 12, "year": 2012, "status": "Submitted", "expenses": [ ...

Resolving TS2304 error using Webpack 2 and Angular 2

I have been closely following the angular documentation regarding webpack 2 integration with angular 2. My code can be found on GitHub here, and it is configured using the webpack.dev.js setup. When attempting to run the development build using npm start ...

Using Conditions in a Javascript For Loop

I would like to utilize a for loop to achieve the following task. Within an array, I have a predefined set of values representing hex colors for a chart. My goal is to extract a specified number of those values using the loop with two options. If the ...

Tips for injecting a service into a class (not a component)

Can you inject a service into a class that is not a component? Consider the following scenario: Myservice import {Injectable} from '@angular/core'; @Injectable() export class myService { dosomething() { // implementation } } MyClass im ...

Ways to reset an input field when focused

Looking to implement a number input field in React that clears the initial value when the user clicks on it. While there are solutions available for text inputs, I have not come across a method for number inputs. Every attempt I make at solving this issu ...

An issue has occurred: Failure to execute spawnSync PATH/target/node/node ENOENTNGCC. Please refer to the

Attempting to initiate my angular project using ./mvnw is resulting in an error when the build runs ng build --configuration development. The error message thrown reads as follows: Generating browser application bundles (phase: setup)... [INFO] /home/use ...

Troubleshooting the issue with the AWS CodeBuild SAM esbuild integration not functioning

I currently have a Lambda's API Gateway repository in CodeCommit that I successfully build using esbuild with CLI (SAM BUILD and then SAM DEPLOY). Now, I am looking to streamline the building process by integrating it with CodePipeline. I started exp ...

Struggling to retrieve the 'this' object using a dynamic string

Within my Nuxt + TS App, I have a method that attempts to call a function: nextPage(paginationName: string): void { this[`${paginationName}Data`].pagination .nextPage() .then((newPage: number) => { this.getData(pagination ...

Retrieving data from a PHP object

I'm facing a challenge trying to extract the genre value from an object generated by this tool library that fetches json data from 'The Movie Database'. I'm currently struggling with Object-oriented PHP and any guidance would be greatly ...

What is the best way to bundle my Language Server along with my client?

Currently, I am in the process of developing a language server for VSCode which consists of both a client and a server that communicate over RPC. Fortunately, the official documentation includes a fully functional example, where the language server is div ...

Tips for serializing an embedded struct to a JSON string using the String() method

package main import ( "fmt" "encoding/json" ) type Ticket struct { From string To string } func (t Ticket) String() string { return fmt.Sprintf("%s - %s", t.From, t.To) } type Passenger struct { Name string `json:"Name"` ...

obtain data from JSON using JavaScript

Greetings! I am dealing with a JSON output that looks like this: "{ \"max_output_watts\": 150, \"frame_length_inches\": \"62.20\", \"frame_width_inches\": \"31.81\" }" I am using it in a functi ...

Sandwich Bot using MS Bot Framework displaying JSON in Command Prompt

Currently, I am using the Microsoft Bot Framework and diligently following their guide (utilizing C# for the .NET version) to construct a Simple Sandwich Bot The initial stages of setting up the bot have been successful. However, upon interacting with the ...