簡體   English   中英

如何將列表從 other.js 文件導入到我的 main.js 文件?

[英]How to import a list from other .js file to my main.js file?

這只是 Ania kubow 的氣候變化 API 中的一個示例。

我的問題是:我有一個這樣的列表,但它更大更長。 我想將該列表存儲在另一個文件中,例如“exampleList.js”,然后我想將其導入到我的 main.js 文件中。

const newspapers = [
    {
        name: 'cityam',
        address: 'https://www.cityam.com/london-must-become-a-world-leader-on-climate-change-action/',
        base: ''
    },
    {
        name: 'thetimes',
        address: 'https://www.thetimes.co.uk/environment/climate-change',
        base: ''
    },
    {
        name: 'guardian',
        address: 'https://www.theguardian.com/environment/climate-crisis',
        base: '',
    },
    {
        name: 'telegraph',
        address: 'https://www.telegraph.co.uk/climate-change',
        base: 'https://www.telegraph.co.uk',
    },
    {
        name: 'nyt',
        address: 'https://www.nytimes.com/international/section/climate',
        base: '',
    },
    {
        name: 'latimes',
        address: 'https://www.latimes.com/environment',
        base: '',
    },
]

然后我想在這里調用它而不是將它寫在同一個文件(main.js)中我不希望代碼看起來凌亂而且太長。 實際上我有更多列表(可能有 3 個列表,每個列表有超過 100 個地址、基數、名稱)我想將它們存儲在不同的文件中。

app.get('/news/:newspaperId', (req, res) => {
    const newspaperId = req.params.newspaperId

    const newspaperAddress = newspapers.filter(newspaper => newspaper.name == newspaperId)[0].address
    const newspaperBase = newspapers.filter(newspaper => newspaper.name == newspaperId)[0].base


    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()
                const url = $(this).attr('href')
                specificArticles.push({
                    title,
                    url: newspaperBase + url,
                    source: newspaperId
                })
            })
            res.json(specificArticles)
        }).catch(err => console.log(err))
})

我試圖創建一個列表文件,然后我嘗試了語句import

import exampleList from (./src/exampleList.js)

它說我需要將"type": "module"添加到我的 package.json 中。 我這樣做了,但它仍然不起作用,它說我無法從模塊中導入語句。 我還嘗試使用 .mjs 和--node-experimental...同樣的事情,但無法正常工作。

首先,確保您正在導出您擁有的列表。 另外,我建議以 JSON 格式存儲數據。

其次,關於您面臨的錯誤

添加"type": "module"到 package.json

查看此問題的主要答案

const newspapers = ["hello"]; module.exports = newspapers; 使用它從文件中導出數據並使用const newspaper = require("./src/exampleList")導入文件並可以使用其他文件中的數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM