首页 > 解决方案 > How can I export array in JS?

问题描述

I'm trying to export and import an array in my javascript chrome extention but it gives me Uncaught SyntaxError: Unexpected token 'export' error.

This is my code:

script.js

const urls = [];
for(var i = document.links.length; i --> 0;)
    if(document.links[i].hostname === location.hostname)
        urls.push(document.links[i].href);

export default urls;

urls.js

import urls from './script.js';

var element = document.querySelector('p');

element.textContent = urls.join('\n');

标签: javascriptgoogle-chrome-extension

解决方案


You need to put type="module" in the HTML <script> tag calling your script.

You could also simplify your code quite a bit, for what it's worth.

let urls = [];

for (const link in Document.links) {
  if (link.hostname === location.hostname) urls.push(link.href)
}

export default urls

推荐阅读