javascript - 使用浏览器化的节点应用程序访问 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]);
解决方案
您需要使用--standalone
标志。如果我重现您在问题中描述的设置并执行:
$ browserify src/index.js --standalone mylib > dist/bundle.js
然后我可以在它上面运行一个交互式节点会话,并以您期望的方式使用该库:
$ node
> require("./dist/bundle").index()
'test'
该--standalone
标志告诉 Browserify 将您的代码包装在UMD 存根中,该存根允许将包加载为 CommonJS 模块、AMD 模块或纯脚本(即不使用模块系统)。您传递的参数--standalone
指示您的库在“纯脚本”情况下将采用什么名称。因此,在上面的示例中,如果您要在没有任何模块系统的浏览器中加载库,您将能够index
以mylib.index()
.
推荐阅读
- css - React Carousel 未显示所有图像
- python - 如何实现将获取字符串列表并将它们解析为元组列表的函数
- python - 创建新的数据框,将另一个数据框的列表列展平
- python - 如何在 Matplotlib 中获取 3D 绘图的 2D 投影版本?
- django - 试图在 django 博客的 CBV 中创建一个访问计数器 + IP 唯一
- prolog - 如何检查变量是否是Prolog中的数字?
- sql - '合并字段' - 类似于 SQL Server 功能
- java - 无法理解此测试用例代码在做什么
- python - 为什么这个while循环不能正确执行
- javascript - 如何为 p5.js 编写一行代码,作为我的播放器的相机跟随器?(var Mover;) 这是一个 2D 游戏