客户端的 JavaScript require()

IT技术 javascript node.js
2021-02-17 00:22:03

是否可以require()在客户端使用(或类似的东西)?

例子

var myClass = require('./js/myclass.js');
6个回答

为此您应该查看require.jshead.js。

@Debra:为什么不去他们网站上的“使用”部分?
2021-04-26 00:22:03
...或者现在您可以将客户端代码与大量工具(例如webpack)捆绑在一起
2021-04-29 00:22:03
如果您想要比 require.js、head.js 或 Lab.js 更轻量级的解决方案,请查看Require()
2021-05-17 00:22:03
当使用requirejs,要注意的告诫:stackoverflow.com/questions/29652716/...否则,对我有用。
2021-05-17 00:22:03

为此,我一直在使用browserify它还允许我将 Node.js module集成到我的客户端代码中。

我在这里写了博客:使用browserify 将 node.js/CommonJS 样式 require() 添加到客户端 JavaScript

如果你想拥有 Node.js 风格,require你可以使用这样的东西:

var require = (function () {
    var cache = {};
    function loadScript(url) {
        var xhr = new XMLHttpRequest(),
            fnBody;
        xhr.open('get', url, false);
        xhr.send();
        if (xhr.status === 200 && xhr.getResponseHeader('Content-Type') === 'application/x-javascript') {
            fnBody = 'var exports = {};\n' + xhr.responseText + '\nreturn exports;';
            cache[url] = (new Function(fnBody)).call({});
        }
    }
    function resolve(module) {
        //TODO resolve urls
        return module;
    }
    function require(module) {
        var url = resolve(module);
        if (!Object.prototype.hasOwnProperty.call(cache, url)) {
            loadScript(url);
        }
        return cache[url];
    }
    require.cache = cache;
    require.resolve = resolve;
    return require;
}());

请注意:此代码有效但不完整(尤其是 url 解析)并且没有实现所有 Node.js 功能(我昨晚刚把它放在一起)。 您不应在实际应用中使用此代码,但它为您提供了一个起点。我用这个简单的module对其进行了测试,它可以工作:

function hello() {
    console.log('Hello world!');
}

exports.hello = hello;
我喜欢这个答案,因为它不是解决方案。当人们只是给出解决方案时,我真的很讨厌它。给出有助于他们下次找到解决方案的答案。很好!
2021-05-14 00:22:03

我问自己同样的问题。当我查看它时,我发现选择势不可挡。

幸运的是,我找到了这个出色的电子表格,可以帮助您根据自己的要求选择最佳加载程序:

https://spreadsheets.google.com/lv?key=tDdcrv9wNQRCNCRCflWxhYQ

我想知道电子​​表格的存在是否意味着我们作为开发人员还没有找到一个很好的方法来做到这一点?
2021-04-27 00:22:03

看看requirejs项目。