最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

只导入一个函数是否也会运行该文件中的其他函数?

网站源码admin30浏览0评论

只导入一个函数是否也会运行该文件中的其他函数?

只导入一个函数是否也会运行该文件中的其他函数?

我在文件中有这段代码

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

我没有在

parseArgument
中导入和使用
index.ts
功能,那为什么会这样呢?我只是将
calculateBmi
函数导入并使用到该文件中。目前,我只能通过注释掉
bmiCalculator.ts
.

中未导出的代码来运行代码 回答如下:

是的,只要你导入一个模块(这里的模块只是一个文件),它就会被执行。

如果模块包含 only 导出函数声明,则没有 side effect.

如果模块包含一些根级表达式(如您的情况中的

const { height, weight } = parseArguments(process.argv);
),它们将被执行。特别是,你应该看到你的下一个
console.log
打印。

发布评论

评论列表(0)

  1. 暂无评论