首页 > 解决方案 > 使用浏览器化的节点应用程序访问 module.exports

问题描述

我们正在尝试浏览我们的节点应用程序

示例文件 (index.js)

module.exports = {
  index: () => 'test',
};

浏览器化命令

browserify src/index.js > dist/bundle.js --node

如果我们使用文件来要求和控制台

console.log(require('src/index'));   // { index: [Function: index] }
console.log(require('dist/bundle')); // { } 

我们的期望是 bundle.js 会像 index.js 一样导出。

谁能指出我们做错了什么或遗漏了什么?


附加信息

~这不是我们的应用程序,这是一个演示问题的示例

我们目前正在将我们的整个应用程序压缩到带有入口点src/index.index的 AWS Lambda,目标是只发送 bundle.js 文件并能够拥有入口点bundle.index

捆绑.js

(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
module.exports = {
    index: () => 'test',
};

},{}]},{},[1]);

标签: javascriptnode.jsaws-lambdabrowserify

解决方案


您需要使用--standalone标志。如果我重现您在问题中描述的设置并执行:

$ browserify src/index.js --standalone mylib > dist/bundle.js

然后我可以在它上面运行一个交互式节点会话,并以您期望的方式使用该库:

$ node
> require("./dist/bundle").index()
'test'

--standalone标志告诉 Browserify 将您的代码包装在UMD 存根中,该存根允许将包加载为 CommonJS 模块、AMD 模块或纯脚本(即不使用模块系统)。您传递的参数--standalone指示您的库在“纯脚本”情况下将采用什么名称。因此,在上面的示例中,如果您要在没有任何模块系统的浏览器中加载库,您将能够indexmylib.index().


推荐阅读