Borislav Hadzhiev

Tue Mar 29 20222 min read


Use an import assertion to solve the error "TypeError [ERR_IMPORT_ASSERTION_TYPE_MISSING]: Module needs an import assertion of type json", e.g. import myJson from './example.json' assert {type: 'json'}. This syntax indicates that the module is JSON and not to be executed.

typeerror err import assertion type missing

Here is an example of how the error occurs.

// ⛔️ TypeError [ERR_IMPORT_ASSERTION_TYPE_MISSING]: Module // "file://bobbyhadz-js/example.json" needs an // import assertion of type "json" import myJson from './example.json';

The line above throws an error because we need to explicitly note that we are importing a JSON module, so it cannot be executed.

import myJson from './example.json' assert {type: 'json'}; // 👇️ { // name: 'Alice', // country: 'Austria', // tasks: [ 'develop', 'design', 'test' ], // age: 30 // } console.log(myJson.person); console.log(myJson.person.name); // 👉️ "Alice" console.log(myJson.person.country); // 👉️ "Austria"

The code snippet above assumes that there is an example.json file in the same directory with the following content:

{ "person": { "name": "Alice", "country": "Austria", "tasks": ["develop", "design", "test"], "age": 30 } }

Note that the type property in your package.json has to be set to module, because we are using ES6 Modules syntax.

{ "type": "module", // ... rest }

Here is a screenshot of the output from running the index.js file.

import json file success

You can read more about why this is necessary in the Import assertions proposal page on GitHub.

In short, the import assertion proposal adds an inline syntax for module import statements.

The syntax was introduced for improved security when importing JSON modules and similar module types which cannot execute code.

This prevents a scenario where a sever responds with a different MIME type, causing code to be unexpectedly executed.

The assert {type: 'json'} syntax enables us to specify that we are importing a JSON or similar module type that isn't going to be executed.

You can read more about the import assertions proposal in this tc39 GitHub repository.

Use the search field on my Home Page to filter through my more than 1,000 articles.