Chrome 61 adds native support for JavaScript Modules

script type="module">
  import {addText} from './utils.js';
  addText('Modules are pretty cool.');
</script>

Google Chrome version 61 adds in native support for Javascript modules, I’m not sure if support existed before but not native of what, however it looks like it’s adding features similar to node.js with the modules. This looks really promising and I’m hoping to utilize it in my future projects. Thoughts?

1 Like

Module support is part of es2015. Developers have been using it for the last 2 years with the help of transpilers. So nothing really new here.

Native module support is a pretty big deal because having to use transpilers sucks. It’d be nice to be able to work without babel.

2 Likes

try it out in chrome canary today - https://www.google.com/chrome/browser/canary.html

no need for canary - I just updated to chrome 61 - it works!

just make sure the page is served from a webserver and not loaded from the local filesystem

wikipedia search in bleeding edge js - classes with async/await in modules!

<!doctype html>
<!-- index.html -->
<head>
<title>Wikipedia Search</title>
</head>
<body>
  <h1>Wikipedia Search</h1>
<p><form>
  <input name=srsearch type=search value=music>
  <input name=action type=hidden value=query>
  <input name=list type=hidden value=search>
  <input name=format type=hidden value=json>
  <input name=formatversion type=hidden value=2>
  <input name=utf8 type=hidden>
  <input name=origin type=hidden value=*>
  <p><output name=out></output>
</form>
<script src=wikisearch.js type=module></script>
<!-- for browsers that do not yet support modules -->
<script nomodule>
document.addEventListener("DOMContentLoaded", ()=>{
  document.querySelector("form").out.innerHTML="<h2>Modules are not supported</h2>"
})
</script>
</body>
</html>

WikiSearch module controls search ui - provides form data to WikiService module to obtain wikipedia results

// wikisearch.js
import {WikiService} from "./wikiservice.js"

class WikiSearch {
  constructor(form, svc) {
    this.form=form
    this.svc=svc
  }
  init() {
    this.form.addEventListener("submit", async e=>{
      e.preventDefault()
      const query=new FormData(this.form)
      const hits=await this.svc.get(query)
      const html=hits? hits.html(): "<p>Wikipedia search failure</p>"
      this.form.out.innerHTML=html
    })
  }
}
document.addEventListener("DOMContentLoaded", ()=>{
  const form=document.querySelector("form")
  const wsvc=new WikiService("https://en.wikipedia.org")
  const wsrch=new WikiSearch(form, wsvc)
  wsrch.init()
})

WikiHits module holds results data - provides data in html table form

// wikihits.js
class WikiHits {
  constructor(src) {
    this.src=src
  }
  get hits() {
    return this.hits_
  }
  set hits(hits) {
    this.hits_=hits
  }
  html() {
    const a=this.hits
    let s=`<p><table>`
    s+="<tr><th>Title<th>Snippet"
    for(let o of a) {
      const href=`${this.src}?curid=${o.pageid}`
      s+=`<tr><td><a href=${href} target=_blank>${o.title}</a>`
      s+=`<td>${o.snippet}`
    }
    s+="</table>"
    return s
  }
}

export {WikiHits}

WikiService module retrieves search hits from wikipedia - returns WikiHits object

// wikiservice.js
import {WikiHits} from "./wikihits.js"

class WikiService {
  constructor(wiki) {
    this.wiki=wiki
    this.api=wiki + "/w/api.php"
  }
  async get(query) {
    try {
      const rsp=await fetch(this.api, {method:"POST", body:query})
      if(!rsp.ok) return null
      const data=await rsp.json()
      const hits=new WikiHits(this.wiki)
      hits.hits=data.query.search
      return hits
    } catch(err) {
      console.log(`fetch error ${err}`)
      return null
    }
  }
}

export {WikiService}

who still thinks this is no big deal?

5 Likes

@ppc ES6+, standard style, no jQuery… I’m in love with your code. :heart_eyes::heart_eyes::heart_eyes:

This is a big deal in my eyes. I am excited to see this gain more popularity, thanks for sharing the snippet.

yeah - write es6 with fear no more since modules are “use strict” only - it’s a great benefit of modules on par with the primary advantage of writing components even for small projects without frameworks and rollups - it’s a fantastic opportunity to learn to program in a modular way from the very beginning - freecodecamp would do well to incorporate modules into its curriculum early

there’s very few code samples with modules - even this little example can easily be split into couple more modules - I did not want to go overboard - I wanted a bit more than 5 lines yet still parseable in a forum post - I wanted to showcase the essentials of import and export - and some great modern javascript features like classes, fetch, async/await etc that help us write code that can be maintained and enhanced in a scalable manner

Except now the support is native, no transpiler needed.

Yeah if you want your app to work only in latest chrome then sure

the <script nomodule> tag as shown in my sample above is understood and ignored by module-enabled browsers - this makes older browsers run fallback code - we can forge ahead with modules for new development and keep older code around for the transition

chrome and safari have modules enabled by default - firefox and edge have it behind flags - details in the browser compatibility chart at MDN

Obviously this is brand new so sites will have to check the user agent and decide which script to load, however over time this will be standardized. Most devices haven’t even auto-updated yet.

There is nomodule tag for module support detection as @ppc correctly mentioned earlier.

Anyway it seems the native module implementation has some problems such as compression of multiple files, lack of tree shaking etc so it’s tricky to use for production level apps.
Here is an article with more details

hi dear , nice club , how can i join your club i am from pakistan too

You can PM me or get details from the club page on my profile