2

I have a react project setup and I want to run some node script on build time to fetch JSON data from external API and save it as a static resource on server and then use that file in the app.

This is the brief overview of the project structure:

src
|-dir
|  |-helpers.ts
|
|-node-script.js

the node script I am trying to run

import fetch from "node-fetch"
import fs from "fs";

fetch('https://jsonplaceholder.typicode.com/todos/1')
    .then((response) => response.json())
    .then((json) => {
        fs.writeFile('./src/data.json', JSON.stringify(json), (err) => {
            if (err) {
                throw new Error('Something went wrong writing the file.')
            }
            console.log('JSON written to file. Contents:', JSON.stringify(json));
        })
    })

This script doesn't run and gives me this error.

(node:62124) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension

I know adding type:module in my package.json resolves this but I don't want to do that as I am afraid it will going to mess with other dependencies in the frontend project.

I am not able to find an alternative solution and need some help here.

Lorem Ipsum
  • 337
  • 2
  • 14
  • Did you check this https://stackoverflow.com/questions/63588714/node9374-warning-to-load-an-es-module-set-type-module – FD3 Nov 06 '22 at 21:40
  • It says right in the console warning, use `.mjs` extension on your node script. Other option would be to use `require` and cjs. – morganney Nov 07 '22 at 00:43
  • @morganney yes it works now but I get in to another problem. I get ```Cannot find module``` error when i try to import some functions from my ```helpers.ts``` file – Lorem Ipsum Nov 07 '22 at 13:57

1 Answers1

0

Try changing your import statements to use require instead

const fetch = require('node-fetch')
const fs = require('fs')
Nathan Shanko
  • 66
  • 2
  • 10