vercel / pkg

Package your Node.js project into an executable
https://npmjs.com/pkg
MIT License
24.33k stars 1.02k forks source link

SyntaxError: Cannot use import statement outside a module #1897

Closed lisxck closed 1 year ago

lisxck commented 1 year ago

What version of pkg are you using?

5.8.1

What version of Node.js are you using?

v18.12.0

What operating system are you using?

Windows

What CPU architecture are you using?

AMD64

What Node versions, OSs and CPU architectures are you building for?

node16-win-arm64, default

Describe the Bug

I want to write code in TypeScript, convert it to JavaScript, and compile it into an exe file

Write code, tsconfig.json, package.json

import axios from 'axios';

const response = await axios.get('https://example.com').then(x => x.data)
console.log(response)
{
    "compilerOptions": {
        "module": "ESNext", // or ES2015, ES2020,
        "moduleResolution": "node",
        "target": "esnext", // or ES2015, ES2020,
        "allowSyntheticDefaultImports": true,
    },
    "ts-node": {
        "esm": true
    }
}
{
  "name": "pkg",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build:win": "npx pkg ./build/index.js -c package.json --debug"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "axios": "^1.3.4"
  },
  "type": "module",
  "pkg": {
    "assets": ["./node_modules/**/*"],
    "outputPath": "./dist"
  }
}

After that, I try to compile it by following the steps below

1, npx tsc index.ts -t "esnext" --moduleResolution "node" -m "esnext" --outDir "build" 2, npm run build:win

I get an error when I run the .exe file I created this way

C:\snapshot\Projects\pkg\build\index.js:1
import axios from 'axios';
^^^^^^

SyntaxError: Cannot use import statement outside a module

A Warning also occurred while compiling

Warning Failed to make bytecode node18-x64 for file

I ran it with the --debug flag, and I could see what it was about.

import utils from './../utils.js';
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at new Script (node:vm:102:7)
    at Socket. ([eval]:18:19)
    at Socket.emit (node:events:537:28)
    at addChunk (node:internal/streams/readable:324:12)
    at readableAddChunk (node:internal/streams/readable:297:9)
    at Readable.push (node:internal/streams/readable:234:10)
    at Pipe.onStreamRead (node:internal/stream_base_commons:190:23)

Node.js v18.5.0

I believe this is an error that occurred when compiling the file and reading the file node _ modules contained in assets.

So far I understand. Is the cause ESM? How can I resolve this?

Expected Behavior

js file created by esm to compile successfully into an executable

To Reproduce

I wrote it in Describe the Bug.

GabenGar commented 1 year ago

Literally a pinned issue: https://github.com/vercel/pkg/issues/1291

robertsLando commented 1 year ago

Follow #1291