Search code examples
javascriptwebpackecmascript-6requirejses6-modules

Require module without webpack etc


How can I load a library that can be loaded only trough require without using webpack, compilation, traspilation, uglification etc.

Let's say: https://github.com/stutrek/scrollMonitor

The code is vanilla javascript and has no external dependencies, however the script cannot be put in the head.

var scrollMonitor = require("scrollmonitor"); // if you're old school you can use the scrollMonitor global.

My preferred option would be to do:

<script src="./scrollMonitor.js"></script>

But that does not work. What is the next easiest option that avoids webpack etc. ?

I tried with ES6 import:

import * as scrollMonitor from './scrollMonitor.js';

But that returns just empty object.

Thanks for help.


Solution

  • Seems like it is possible using getlibs package:

    <!-- index.html -->
    <html>
    <body>
        <script src="https://unpkg.com/getlibs"></script>
        <script>
             System.import("./script.js");
        </script>
    </body>
    </html>
    
    // script.js
    console.log(require('scrollmonitor'));
    

    Working example: https://glitch.com/edit/#!/aromatic-flamingo

    In the script above scrollmonitor is loaded from https://unpkg.com/ however this method works also with local files. I think that solves my problem fully.

    Another solution seems to be Pika-Web:

    A Future Without Webpack

    @pika/web installs modern npm dependencies in a way that lets them run natively in the browser, even if they have dependencies themselves. That’s it. It’s not a build tool and it’s not a bundler (in the traditional sense, anyway). @pika/web is a dependency install-time tool that lets you dramatically reduce the need for other tooling and even skip Webpack or Parcel entirely.

    It all comes down to a tradeoff between performance, caching efficiency, and how much complexity you feel comfortable with. And again, this is the entire point of @pika/web: Add a bundler because it makes sense to your situation, not because you have no other choice.

    @pika/web checks your package.json manifest for any "dependencies" that export a valid ESM “module” entry point, and then installs them to a local web_modules/ directory. @pika/web works on any ESM package, even ones with ESM & Common.js internal dependencies.

    https://www.pika.dev/blog/pika-web-a-future-without-webpack/

    However, it works only with a valid ESM "module" entry point. Not the case with scrollMonitor.