1
votes

I've this html page with a module ...

<html>
    <body>
        <hello-world color="blue" />
        <hello-world color="red" />
        <hello-world />
        <script type="module">
            import { HelloWorld } from './HelloWorld.js'
            window.customElements.define('hello-world', HelloWorld)
        </script>
    </body>
</html>

... and the module content is ...

export class HelloWorld extends HTMLElement {
    get color () {
        return this.getAttribute('color') || 'gray'
    }

    set color (value) {
        this.setAttribute('color', value)
    }

    connectedCallback() {
        window.requestAnimationFrame(() => {
            const div = document.createElement('div')
            div.textContent = 'Hello World!!!'
            div.style.color = this.color
            this.appendChild(div)
        });
    }
}

I run a PHP server using php -S localhost:8888 -t . and all works fine:

enter image description here

Instead, ... if I move module in ./main.mjs file with content ...

import { HelloWorld } from './HelloWorld.js'
window.customElements.define('hello-world', HelloWorld)

... changing the html part in ...

<html>
    <body>
        <hello-world color="blue" />
        <hello-world color="red" />
        <hello-world />
        <script type="module" src="main.mjs"></script>
    </body>
</html>

... I get the following error:

Failed to load module script: The server responded with a non-JavaScript MIME type of "". Strict MIME type checking is enforced for module scripts per HTML spec.

Why? May I fix it? How?

2

2 Answers

0
votes

You may send the proper content-type (text/javascript) to specify you are sending js files.

exemple with a basic server in node:

const http = require('http');
const fs = require('fs')
const requestListener = function (req, res) {
  f = req.url === '/' ? 'index.html' : 'main.mjs'

  // commenting that block will give an empty mime type and module will not be loaded
  if (f === 'main.mjs') {
    res.setHeader('Content-type', 'text/javascript')
  }
  res.writeHead(200)
  return fs.createReadStream(f).pipe(res)
}

const server = http.createServer(requestListener);
server.listen(8080);
console.log('listening: http://localhost:8080')

index.html

<!DOCTYPE html>
<html>
<body>
  <div id="junk">loading failed</div>
  <script type="module" src="main.mjs"></script>
</body>
</html>

main.js

document.getElementById('junk').innerHTML = 'loading ok'

see Troubleshooting

0
votes

PHP's simple built-in server doesn't have a MIME type registered for .mjs files. It's not a common extension and is typically only used for ES6 modules in Node.js (and isn't needed there any more thanks to the type option in package.json).

Rename the file to have a .js extension again and your HTTP server will send the correct Content-Type for it.