javascriptjsonimport

Static import of JSON object specifying the type


I have a small javascript web-application that I develop on my laptop and is later bundled with webpack for publishing. In some files, some JSON-data is imported right in the "header" of the file e.g.

import {default as PRICE_LIST} from '../prices/ArticlePrice.json' assert { type: "json"};

Until some months ago, there was no problem with that, then the browser (I use mostly Opera on macOS) started to show me a warning regarding assert that soon it would not be supported anymore. Now, after the most recent update, it really shows an error and does not load SyntaxError: Unexpected identifier 'assert' (at ....). Strangely (or maybe I am just missing what webpack does) the bundled code still runs without problems in the same browser.

A quick research showed me following answer on SO which actually has slightly different use-case, but solves the problem.

import {default as PRICE_LIST} from '../prices/ArticlePrice.json' with { type: "json"};

But now VisualStudioCode claims, that with would be an error, so I am wondering what is correct now? The type declaration is, so far I have understood this, anyway more good practice than really needed, should I remove it altogether? I have found little documentation about the use of assert and none at all for with (well it is a hard word to google because it is always found)


Solution

  • The old import ... assert { type: 'json' } syntax was called "import assertions". It was renamed to "import attributes" and the syntax was changed to import ... with { type: 'json' }, though without any change to the actual behaviour.

    Your editor is simply showing an error based on an out of date knowledge of JavaScript syntax, whereas your browser is correctly accepting the new syntax.

    Of course, some users' browsers - about 20% of them at the time that I write this answer - will also be too old to support the new syntax with with. See the MDN compatibility table about import syntax and the Can I Use... page for with {type: 'json'} in particular for detail on what browser versions support the syntax.

    If you want to support browsers that aren't cutting edge, consider either:

    Either way, you avoid needing to use either import ... assert or import ... with and thus dodge the compatibility problems posed by either.