包括使用webpack编译的捆绑软件,以在另一个js文件中使用

时间:2019-11-30 20:57:09

标签: javascript node.js webpack

我的应用具有以下结构:

index.js

const app = require("./app")
exports.api = app(...)

app.js

//all the imports goes here
//and exporting the main function
module.exports = app => {...}

现在我需要将app.js与webpack捆绑在一起,但是index.js必须保持完整

问题是,在捆绑app.js之后,如何require appindex.js中的主要功能?{p>

在进行app.js网络打包后,我在index.js中遇到错误,提示“ app不是函数”,这是有道理的,因为app.js内容现在被打包在webpack职员中。

任何建议都值得赞赏。

2 个答案:

答案 0 :(得分:2)

您的“应用”捆绑包需要导出为commonjs

module.exports = {
  //...
  output: {
    library: 'app',
    libraryTarget: 'commonjs',
  }
};
  

您的入口点的返回值将使用output.library值分配给导出对象。顾名思义,它用于CommonJS环境。

因此,在您的index.js中,您可以require('./dist/bundle-name.js')

答案 1 :(得分:0)

似乎是黑客,但我通过添加一个中间文件并像下面这样调整app.jsindex.js使其起作用:

index.js

const app = require("./bundle").app //changed to named import
exports.api = app(...)

bundle.js //中间文件,现在是webpack的入口点

import app from "./app"
exports.app = app

app.js

//all the imports goes here
//and exporting the main function
export default app => {...} //changed to default export

如果有人对为什么这样做有解释,以及如何在不添加bundle.js文件的情况下简化它,欢迎您发表评论!