Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a standalone cli script using a nextjs project?

I have an working nextjs project.

I need to create a script that I can run from the CLI that uses some of the CRUD libraries I've written for the next project.

**/scripts/backup-assets.js **

import {getAllProjectsData} from '../lib/api/projects'

async function main() {
  const allProjectsData = await getAllProjectsData()
  console.info({allProjectsData})
}

main()

I'm getting this error:

$ node scripts/backup-assets.js 
(node:9736) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
C:\Users\...\scripts\backup-assets.js:1
import {getAllProjectsData} from '../lib/api/projects'
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at Object.compileFunction (node:vm:352:18)
    at wrapSafe (node:internal/modules/cjs/loader:1033:15)
    at Module._compile (node:internal/modules/cjs/loader:1069:27)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1159:10)
    at Module.load (node:internal/modules/cjs/loader:981:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12)
    at node:internal/main/run_main_module:17:47
like image 839
twangsta Avatar asked Sep 14 '25 10:09

twangsta


1 Answers

Use TSX. It runs out of the box with NextJS, with both JavaScript and TypeScript.

Install it:

npm install --save-dev tsx

Declare your script. In package.json:

...
"scripts": {
  ...
  "my-js-script": "tsx scripts/my-script.js",
  "my-ts-script": "tsx scripts/my-script.ts"
},

Run it:

npm run my-js-script
npm run my-ts-script
like image 150
philippe_b Avatar answered Sep 15 '25 23:09

philippe_b