我正在尝试使用 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(...) 是 webpack 在编译所有 js 文件时在 main.js 中创建的东西,但我不知道那里可能出了什么问题。
最佳答案
问题在于您的导出:
module.exports = { foo };
这是一个shorthand notation用于写作
module.exports = {
foo: foo,
};
也就是说,一个具有单个键 "foo"
的对象,其函数的值名为 foo
。
当您稍后需要该模块时,您将尝试调用模块导出,这不是函数,而是它周围的对象。如果您只想导出单个函数并导入单个函数,您可以这样做:
module.exports = foo;
关于javascript - 使用Webpack编译js文件时出现 "Uncaught TypeError",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58530593/