[Vuejs]-Vue.js don't work with external JSON in HTML file

0👍

The problem is you’re using ECMAScript Imports outside of a module script. The import keyword is only recognized inside <script type="module">, so your usage would result in a syntax error: Unexpected identifier on the line of your import statement (where you try to import json/products.json).

There are a couple solutions that require a modern browser (and polyfills for older browsers).

OPTION 1: Change your script to include type="module", and make sure to use relative paths in the import path. demo

<!-- inside HTML file -->
<script type="module">
  import products from './json/products.json.js'

  new Vue({
    el: '#app',
    data () {
      return {
        items: products
      }
    }
  })
</script>

OPTION 2: Fetch the external JSON file instead of importing it. demo

<!-- inside HTML file -->
<script>
  (async () => {
    const productsResponse = await fetch('./json/products.json');
    const products = await productsResponse.json();

    new Vue({
      el: '#app',
      data () {
        return {
          items: products
        }
      }
    })
  })();
</script>

Alternatively, you could switch to vue-cli projects, which includes transpiling in its build, allowing you to use imports for external JSON files. demo

Leave a comment