Javascript 包括使用webpack编译的捆绑包,以便在另一个js文件中使用
我的应用程序具有以下结构: index.jsJavascript 包括使用webpack编译的捆绑包,以便在另一个js文件中使用,javascript,node.js,webpack,Javascript,Node.js,Webpack,我的应用程序具有以下结构: index.js const app = require("./app") exports.api = app(...) //all the imports goes here //and exporting the main function module.exports = app => {...} const app = require("./bundle").app //changed to named import exports.api = ap
const app = require("./app")
exports.api = app(...)
//all the imports goes here
//and exporting the main function
module.exports = app => {...}
const app = require("./bundle").app //changed to named import
exports.api = app(...)
//all the imports goes here
//and exporting the main function
export default app => {...} //changed to default export
app.js
const app = require("./app")
exports.api = app(...)
//all the imports goes here
//and exporting the main function
module.exports = app => {...}
const app = require("./bundle").app //changed to named import
exports.api = app(...)
//all the imports goes here
//and exporting the main function
export default app => {...} //changed to default export
现在我需要将app.js
与webpack捆绑在一起,但是index.js
必须保持完整
问题是,在捆绑了app.js
之后,我如何从index.js
中要求它的主要功能app
在webpackapp.js
之后,我在index.js
中发现了一个错误,上面说“app不是一个函数”,这是有道理的,因为app.js的内容现在被包装在webpack中
非常感谢您的建议。您的“应用程序”捆绑包需要作为文件导出
入口点的返回值将使用output.library值指定给导出对象。顾名思义,这在CommonJS环境中使用
因此,在您的index.js
中,您可以要求('./dist/bundle name.js')
似乎是一个黑客行为,但我通过添加一个中间文件并调整app.js
和index.js
使之生效,如下所示:
index.js
const app = require("./app")
exports.api = app(...)
//all the imports goes here
//and exporting the main function
module.exports = app => {...}
const app = require("./bundle").app //changed to named import
exports.api = app(...)
//all the imports goes here
//and exporting the main function
export default app => {...} //changed to default export
bundle.js//一个中间文件,现在是webpack的入口点
import app from "./app"
exports.app = app
app.js
const app = require("./app")
exports.api = app(...)
//all the imports goes here
//and exporting the main function
module.exports = app => {...}
const app = require("./bundle").app //changed to named import
exports.api = app(...)
//all the imports goes here
//and exporting the main function
export default app => {...} //changed to default export
如果有人解释了为什么它是这样工作的,以及如何在不添加bundle.js
文件的情况下简化它,欢迎您发表评论 谢谢你的意见!请详细说明index.js中应该包含哪些内容来使用它?我试图以不同的方式导入它,但到目前为止无法让它工作(它是针对nodejs的)。app.js中导出的任何内容都将作为“MyLibrary”提供,请阅读文档。我确实阅读了文档,除非我读错了,否则没有多大帮助。你能举个例子说明你将如何导入它吗?我已经更新了我的答案,注意我已经更改了libraryTraget
谢谢@felixmosh,现在可以了!唯一需要提及的是,webpack在根目录下创建了一个命名导入,在本例中,导入过程如下:require('./dist/bundle name.js').app(或配置中的任何“library”名称)