是否可以require()
在客户端使用(或类似的东西)?
例子
var myClass = require('./js/myclass.js');
是否可以require()
在客户端使用(或类似的东西)?
例子
var myClass = require('./js/myclass.js');
为此,您应该查看require.js或head.js。
为此,我一直在使用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;
我问自己同样的问题。当我查看它时,我发现选择势不可挡。
幸运的是,我找到了这个出色的电子表格,可以帮助您根据自己的要求选择最佳加载程序:
https://spreadsheets.google.com/lv?key=tDdcrv9wNQRCNCRCflWxhYQ
看看requirejs项目。