需要没有 webpack 等的模块

Require module without webpack etc

如何在不使用 webpack、编译、traspilation、uglification 等的情况下加载只能通过 require 加载的库

假设: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.

我的首选是:

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

但这不起作用。避免 webpack 等的下一个最简单的选择是什么?

我尝试使用 ES6 导入:

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

但是 returns 只是一个空对象。

感谢您的帮助。

My preferred option would be to do:

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

But that does not work.

库支持此变体,但不应将其放入 head。只需尝试将其添加到 body 的末尾即可。全局变量 scrollMonitor 也应该出现。

似乎可以使用 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'));

工作示例:https://glitch.com/edit/#!/aromatic-flamingo

在上面的脚本中,scrollmonitor 是从 https://unpkg.com/ 加载的,但是此方法也适用于本地文件。我认为这完全解决了我的问题。

另一个解决方案似乎是 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.pikapkg.com/blog/pika-web-a-future-without-webpack

但是,它仅适用于有效的 ESM“模块”入口点。 scrollMonitor 不是这种情况。

该软件包包含一个后备全局,因此您可以这样做:

import './scrollMonitor';

这使得 scrollMonitor 在 window 对象上可用,供您使用。