antfu / vite-ssg

Static site generation for Vue 3 on Vite

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Error [ERR_UNSUPPORTED_DIR_IMPORT] importing date-fns/locale

ChrisGV04 opened this issue · comments

Hi! I'm currently using date-fns on my vite / vue app for date formatting and I'm also using the locale for spanish. For some reason when I run npm run build I get the error:
Error [ERR_UNSUPPORTED_DIR_IMPORT]: Directory import '/my-project-directory/node_modules/date-fns/locale' is not supported resolving ES modules imported from /my-project-directory/.vite-ssg-temp/main.mjs and it suggests Did you mean to import date-fns@2.28.0/node_modules/date-fns/locale/index.js?

This is weird because I have been using this exact same code with older versions and it worked perfectly, also when I run npm run dev everything works fine. The last version of vite-ssg I tried and builds with no problem is 0.17.6. I'm also using date-fns version 2.28.0

This is my build script in the package.json: "build": "cross-env NODE_ENV=production vite-ssg build"

@ChrisGV04 since we move to esm from version 0.17.0 just try adding format: 'cjs' on ssgOptions. If still not working you should request upgrade date-fns repo to support esm , it is not configured to support new node esm resolution.

You can check this issue, there are some hints there about esm support: #201

@ChrisGV04 maybe you can check https://nodejs.org/api/intl.html, you can use Intl on node.

@userquin Thank you very much for both of your replies!

I made some more research with the information you shared about esm and I was able to fix it by changing the import path of the locale to the following:

import es from "date-fns/locale/es/index.js"

That seems to work fine and it also builds the project without any issues.

If this is bad practice or there's some reason for not doing that, please let me know! Thank you very much.

I also tried Intl and it does work for most of my needs, but unfortunately I do need date-fns for more than just formatting dates. But thanks for the recommendation, I will certainly start using it more!

@ChrisGV04

If this is bad practice or there's some reason for not doing that, please let me know! Thank you very much.

Importing the dependency this way you are bundling the full dependency: date-fns should be upgraded to support esm and including sideEffects to avoid this.

You can try building your app, check the chunks size, then modify the date-fns' package.json adding "type": "module", "sideEffects": "false" (this should be checked) and "exports" entries, then change the import on your codebase and compare the build result: check this issue entry mrdoob/three.js#16059 (comment)

Don't forget to undo changes made on date-fns' package.json file.