2

I have file1, data.js:

export var data = [
    {
        id : "001",
        name : "apple",
        category : "fruit",
        color : "red"
    },
    {
        id : "002",
        name : "melon",
        category : "fruit",
        color : "green"
    },
    {
        id : "003",
        name : "banana",
        category : "fruit",
        color : "yellow"
    }
]

module.exports = data;

And I have file2, index.html:

<table id="table">
    <tr>
        <th>ID</th>
        <th>Name</th>
        <th>Category</th>
        <th>Color</th>
    </tr>
</table>


<script src="jquery.js"></script>
<script>
import {data} from 'data.js';

for(var i = 0; i < data.length; i++) {
    var row = '<tr><td>' + data[i].id + '</td>';
    row+= '<td>' + data[i].name+ '</td>';
    row+= '<td>' + data[i].category + '</td>';
    row+= '<td>' + data[i].color + '</td></tr>';
    $("#table").append(row);
}
</script>

The problem is with this line:

import {data} from 'data.js';

If I include the data var directly in index.html, it works fine, but when I try to reference it from it's own separate file it doesn't work.

The error it throws is:

  Unexpected token { import call expects exactly one argument

1 Answer 1

1

Use script tag instead of import. Remove export in js file.

  <script type="text/javascript" src="data.js"></script>

1.html

<table id="table">
  <tr>
    <th>ID</th>
    <th>Name</th>
    <th>Category</th>
    <th>Color</th>
  </tr>
</table>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript" src="data.js"></script>
<script>
  for (var i = 0; i < data.length; i++) {
    var row = "<tr><td>" + data[i].id + "</td>";
    row += "<td>" + data[i].name + "</td>";
    row += "<td>" + data[i].category + "</td>";
    row += "<td>" + data[i].color + "</td></tr>";
    $("#table").append(row);
  }
</script>

data.js

var data = [
  {
    id: "001",
    name: "apple",
    category: "fruit",
    color: "red",
  },
  {
    id: "002",
    name: "melon",
    category: "fruit",
    color: "green",
  },
  {
    id: "003",
    name: "banana",
    category: "fruit",
    color: "yellow",
  },
];

Sign up to request clarification or add additional context in comments.

3 Comments

This totally works -- but curious if there is just some syntax I'm using wrong to import the data var directly?
You cannot use import outside of module.
For more explanation, please check this: jakearchibald.com/2017/es-modules-in-browsers

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.