Cannot use import statement outside a module.

Why I get this error? The express app is working and building fine locally.

I forget the details of this and Node but I suspect it’s related to the version of Node being run within Fly.

I can’t tell what Dockerfile or buildpack you have setup but I suspect you’re running a different version of Node locally

I’ve been running tests on various versions of node, including the latest: node 19. In all it comes down to making sure the package.json specifies type “module”: Modules: Packages | Node.js v19.0.0 Documentation (nodejs.org)

@antonjones I don’t know how you are building locally, but undoubtedly you are not using buildpacks. Can you describe how you are building locally? And verify that you are specifying type module in your package.json?

2 Likes

I am using babel ^7 to build it. It seems like babel issue but I dunno how to fix it. Here is my package.json file


OK, so babel is doing the conversion, and we aren’t running babel.

You won’t have to fix anything.

What’s the exact command you are using to build? Should be something like npm run build or yarn build.

I am using yarn build. The import is working in dist/index.js but it is not working in subdirectories like dist/auth/index.js. I tried like 1000 ways

I have more cleanup and testing to do, but if you have time give this a try.

At this point, you likely have have something like the following in your fly.toml, and if so, remove it as it isn’t doing what you need:

[build]
  builder = "heroku/buildpacks:20"

Now create/replace your Dockerfile with:

FROM debian:bullseye 

ARG NODE_VERSION=18.10.0
ARG YARN_VERSION=1.22.19

RUN apt-get update; apt install -y curl
RUN curl https://get.volta.sh | bash
ENV VOLTA_HOME /root/.volta
ENV PATH $VOLTA_HOME/bin:/usr/local/bin:$PATH
RUN volta install node@${NODE_VERSION} yarn@${YARN_VERSION}

#######################################################################

RUN mkdir /app
WORKDIR /app

ENV HOST 0.0.0.0
ENV PORT 8080
ENV NODE_ENV production

COPY . .

RUN yarn install && yarn run build

CMD [ "yarn", "run", "start" ]

Feel free to adjust the values of NODE_VERSION and YARN_VERSION.

Once this is working, I plan to handle more cases (you have a build step yes/no? You use yarn or npm?) and cleanup (some build artifacts aren’t needed at runtime, and smaller images load fater), and then change flyctl launch to produce something that works.