使用Webpack编译js文件时出现“未捕获的TypeError”

问题描述 投票:1回答:1

我正在尝试使用Webpack创建一个简单的node.js应用程序来编译我的javascript文件。我对node.js完全陌生,因此我很难理解自己在做什么以及应该如何做。

很抱歉,这确实需要花很多时间,但是我在配置方面遇到了麻烦,而且我不确定是哪个特定文件引起了问题,因此我发布了很多代码。非常抱歉。

到目前为止,我的应用程序体系结构如下:

app

 └─app.js
 └─package.json
 └─package-lock.json  
 └─webpack.config.js
 └─views
 |  └─index.ejs
 └─public 
    └─javascript
       └─scripts //where I put functions i am importing into index.js
       |   └─foo.js
       |   └─bar.js
       └─index.js //file with all js functions create
       └─main.js //bundle made by webpacker

在我的app.js文件中:

 const path = require("path");
 const express = require("express");
 const port = process.env.PORT || "8000";

 const app = express();
 app.set("view engine", "ejs");
 app.use(express.static("public"));

在我的public / javascript / scripts / foo.js中:

 const foo = () => {
   ....
 };

 module.exports = { foo };

在我的public / javascript / index.js中:

 const foo = require("./scripts/foo");

 foo();

在我的webpack.config中:

 const path = require("path");
 module.exports = {
   context: __dirname,
   entry: "./public/javascript/index.js",
   output: {
     path: path.resolve(__dirname, "public/javascript"),
     filename: "main.js"
   },
   watch: true
 };

以及在我的views / index.ejs:

 <!DOCTYPE html>
 <html lang="en">
   <head>
     <meta charset="UTF-8" />
     <title>Objects</title>
     <link rel="stylesheet" type="text/css" href="/css/style.css" />
   </head>
   <body>
     ...
     <script type="text/javascript" src="/javascript/main.js"></script>
   </body>
 </html>

然后我用以下命令启动服务器:

nodemon ./app.js

并使用以下命令启动客户端:

webpack --config ./webpack.config.js

html在浏览器中加载得很好,但是javascript无法正常运行,并且控制台打印:

Uncaught TypeError: r(...) is not a function
    at Object.<anonymous> (main.js:1)
    at r (main.js:1)
    at main.js:1
    at main.js:1

r(...)是在main.js中编译所有js文件时创建的Webpack,但我不知道那里可能有什么问题。

javascript node.js webpack
1个回答
0
投票

问题是您的出口:

module.exports = { foo };

这是用于写作的shorthand notation

module.exports = {
    foo: foo,
};

即,具有单个键"foo"且对象的函数名称为foo的对象。

[以后需要模块时,您将尝试调用模块导出,它不是函数,而是周围的对象。如果您只想导出单个函数并导入单个函数,则可以执行以下操作:

module.exports = foo;
© www.soinside.com 2019 - 2024. All rights reserved.