如何将列表从其他.js文件导入main.js?Node.js模块导入问题
Node.js ES模块导入解决方案(适配Ania Kubow气候变化API项目)
核心步骤解决导入问题
1. 正确导出独立列表文件
在src/exampleList.js中使用ES模块语法导出你的列表,二选一即可:
- 命名导出(推荐,便于同时导出多个列表):
// src/exampleList.js export const newspapers = [ { name: "nytimes", address: "https://www.nytimes.com/", base: "https://www.nytimes.com" }, // 其余100+条数据 ]; // 若有其他列表,可一并导出 export const magazines = [/* 数据 */];
- 默认导出:
// src/exampleList.js const newspapers = [/* 数据 */]; export default newspapers;
2. 匹配导入语法到main.js
根据导出方式选择对应导入写法:
- 对应命名导出:
// main.js(项目根目录下) import { newspapers } from './src/exampleList.js';
- 对应默认导出:
// main.js(项目根目录下) import newspapers from './src/exampleList.js';
3. 配置package.json启用ES模块
确保项目根目录的package.json中包含顶层的"type": "module"字段,无需修改文件后缀或添加实验性参数:
{ "name": "climate-news-api", "version": "1.0.0", "type": "module", "dependencies": { "axios": "^1.6.0", "cheerio": "^1.0.0-rc.12", "express": "^4.18.2" } }
4. 校验文件路径
确认导入路径为正确的相对路径:
- 若main.js在根目录,exampleList.js在
src文件夹下,必须写./src/exampleList.js(开头的.不能省略) - 路径区分大小写,需确保文件名和文件夹名拼写完全一致
额外代码优化(可选)
原代码中两次调用filter遍历数组,可改为一次find提升性能,同时增加错误处理逻辑:
app.get('/news/:newspaperId', (req, res) => { const newspaperId = req.params.newspaperId // 单次遍历找到目标报纸 const newspaper = newspapers.find(item => item.name === newspaperId) // 处理报纸不存在的异常情况 if (!newspaper) { return res.status(404).json({ error: "指定报纸不存在" }) } // 解构赋值简化代码 const { address: newspaperAddress, base: newspaperBase } = newspaper axios.get(newspaperAddress) .then(response => { const html = response.data const $ = cheerio.load(html) const specificArticles = [] $('a:contains("climate")', html).each(function () { const title = $(this).text().trim() const url = $(this).attr('href') specificArticles.push({ title, url: newspaperBase + url, source: newspaperId }) }) res.json(specificArticles) }).catch(err => { console.error(err) res.status(500).json({ error: "获取新闻失败" }) }) })
内容的提问来源于stack exchange,提问作者Imad Eddine
相关产品推荐
相关产品推荐

