javascriptnode.jselectronlit-html

How do I properly load the lit-html module in Electron


I'm trying to use lit-html to save my self some time, but I'm having trouble getting everything set up correctly.

Electron 4.1.1

Node 11.15

As of 5 minutes before posting this, I've run npm install and electron-rebuild, no luck.

I use require() as one would with any other NPM package

var render = require('lit-html').render
var html = require('lit-html').html
console.log(require("lit-html"))

Unfortunately, I'm greeted with this errorenter image description here In reference to the three lines of code above.

I don't see any problems with my code.

I've tried reinstalling lit-html through NPM to no avail. I would really love to use this library, but first I have to get over this hurdle. If I'm being honest, I don't know if this error is reproducible, but nothing I do seems to fix it. The problem seems to lie with node and the way that imports are handled.

Am I missing something here? Is this a common issue? If so, what can I do to fix it?


Solution

  • You need to transpile lit-html before you can require it

    I tested require('lit-html') and I was greeted with this error:

    /path/to/project/node_modules/lit-html/lit-html.js:31
    import { defaultTemplateProcessor } from './lib/default-template-processor.js';
    

    It clearly states that the error is coming from lit-html/lit-html.js:31 where the line uses ES Module import syntax.

    You can transpile it using tools like Babel or similar ones. However, you may want to try using ES Module syntax so you can import lit-html without transpiling it.

    Example:

    <!-- HTML File -->
    <script type="module" src="index.js"></script>
    
    // index.js
    import { html } from 'lit-html';
    

    What if you can't use type="module"

    If you are unable to use the type="module" method above, you can also use the ESM package (possibly outdated).

    ESM is a brilliantly simple, babel-less, bundle-less ECMAScript module loader.

    Here are a few examples of how to use it:

    1. Using the node require flag (-r) to load esm before everything else
    node -r esm index.js
    
    1. Loading esm in your main file then loading the rest of your code.
    // Set options as a parameter, environment variable, or rc file.
    require = require('esm')(module/*, options*/)
    module.exports = require('./main.js')