我在文件 bmiCalculator.ts
中有此代码:
import { isNotNumber } from './utils';
export default function calculateBmi(height: number, weight: number) {
const bmi = weight / Math.pow(height / 100, 2);
if (bmi < 18.5) {
return 'Underweight';
} else if (bmi >= 18.5 && bmi < 25) {
return 'Normal (healthy weight)';
} else {
return 'Overweight';
}
}
const parseArguments = (args: string[]) => {
if (args.length < 4) throw new Error('Not Enough Arguments');
if (args.length > 4) throw new Error('Too many arguments');
if (!isNotNumber(args[2]) && !isNotNumber(args[3])) {
return {
height: Number(args[2]),
weight: Number(args[3]),
};
} else {
throw new Error('Arguments are not of the correct type');
}
};
const { height, weight } = parseArguments(process.argv);
console.log(calculateBmi(height, weight));
还有文件 index.ts
中的这段代码:
import express from 'express';
import calculateBmi from './bmiCalculator';
const app = express();
app.get('/hello', (_req, res) => {
res.send('Hello Full Stack!');
});
app.get('/bmi', (req, res) => {
const height = Number(req.query.height);
const weight = Number(req.query.weight);
const bmi = calculateBmi(height, weight);
res.send({ weight, height, bmi });
});
const PORT = 3002;
app.listen(PORT, () => console.log(`server running on port ${PORT}`));
在 index.ts
中运行 Express 服务器代码时出现以下错误:
Error: Not Enough Arguments
我没有在 index.ts
中导入和使用 parseArgument
函数,那么为什么会发生这种情况?我仅将 calculateBmi
函数导入并使用该文件。目前,我只能通过注释掉 bmiCalculator.ts
中未导出的代码来运行代码。
最佳答案
是的,只要你导入一个模块(这里的模块只是一个文件),它就会被执行。
如果模块仅包含导出函数声明,则不会有副作用。
如果模块包含一些根级表达式(如您的情况下的const { height,weight } = parseArguments(process.argv);
),它们就会被执行。特别是,您应该看到下一个 console.log
打印。
关于javascript - 仅导入一个函数是否也会运行该文件中的其他函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76138098/