javascriptimporthookofflinepreact

Import preact hooks module locally (offline)


I am trying to use preact hooks in my web application. I am going through no build tools route. Following is the code I am using to do the job

import { h, render, Component } from './preact.mjs';
import { useState } from './hooks.mjs';
import { htm } from './htm.mjs';

const html = htm.bind(h);

function MyComponent() {
    return html`<button>Click Me!</button>`
}

render(html`<${MyComponent}/>`, document.getElementById("root"));

But I am getting following error in browser console

Uncaught TypeError: The specifier “preact” was a bare specifier, but was not remapped to anything. Relative module specifiers must start with “./”, “../” or “/”.

I believe below line in hooks.mjs is the cause for problem. It is not referencing preact.mjs but just preact

import{options as n} from "preact";

How to solve this. I do not want to manually modify this line but use it as is. There should be a reason why the default library is shipped as it. Am I missing something here.

PS: I cannot use CDN. I need to use this in a system without internet connection.


Solution

  • Where are you getting the code for preact.mjs and hooks.mjs from? If you're copy/pasting from NPM, the published content is meant for consumption in Node/environments that support Node's module resolution. This is not usable directly in the browser.

    However, what you can use are import maps, which support this behavior. Simply insert this in the head of the document, before you import your script:

    <script type="importmap">
        {
            "imports": {
                "preact": "./preact.mjs",
                "preact/hooks": "./hooks.mjs"
            }
        }
    </script>
    

    This will map preact to ./preact.mjs, correcting the specifiers to avoid errors.