Snowpack cannot import JavaScript from node_modules

722 views Asked by At

I'm currently using Snowpack to build/prepare an application. I'm trying to import a JavaScript library I installed as part of the dependencies (block) in the package.json file, but somehow Snowpack is not picking up the library.

This is (an excerpt with the relevant content of) the package.json file:

{
  "private": true,
  "type": "module",
  "scripts": {
    "build": "snowpack build",
    "preview": "snowpack dev"
  },
  "dependencies": {
    "impress.js": "1.1.0"
  },
  "devDependencies": {
    "snowpack": "3.3.7"
  },
  "engines": {
    "node": "14.x"
  }
}

The snowpack.config.js only contains these lines:

/** @type {import("snowpack").SnowpackUserConfig } */
export default {
  devOptions: {
    open: "none",
  },
  mount: {
    src: {
      url: "/",
    },
  },
};

I was expecting Snowpack to bundle the impress.js library with this HTML file:

<!DOCTYPE html>
<html lang="en">
  <head>
    ...
  </head>
  <body>
    <script src="node_modules/impress.js/js/impress.min.js"></script>
    <script src="scripts/global.js" type="module"></script>
  </body>
</html>

Is there a way to configure Snowpack for such things?

2

There are 2 answers

0
x80486 On BEST ANSWER

In case somebody come across something similar to this, the way I found to bundle Impress.js (and probably any other library that has/hasn't been modularized) is to just import it in the JavaScript file (notice the type="module" in the HTML script tag):

<!DOCTYPE html>
<html lang="en">
  <head>
    ...
  </head>
  <body>
    <script src="scripts/global.js" type="module"></script>
  </body>
</html>
import "impress.js";

impress(); // ...bootstraps/initializes Impress.js
1
Aaron A. On

If you simply want to convert the Impress module to ESM have you considered trying esinstall?

i.e.

convert.mjs:

import {install} from 'esinstall';
await install(['impress.js'], {});
node convert.mjs

and then in your HTML file:

 <script src="web_modules/impress.js"></script>