All is fine with using ES6 such as this import:
import sde from '../path-to/sde.json'
But when I include the assert (which I require for different reasons (monorepo)) such as:
import sde from '../path-to/sde.json' assert {type:'json'}
I get the following error when envoking the function:
{
"errorType": "Runtime.UserCodeSyntaxError",
"errorMessage": "SyntaxError: Cannot use import statement outside a module",
"trace": [
"Runtime.UserCodeSyntaxError: SyntaxError: Cannot use import statement outside a module",
" at _loadUserApp (file:///var/runtime/index.mjs:1058:17)",
" at async UserFunction.js.module.exports.load (file:///var/runtime/index.mjs:1093:21)",
" at async start (file:///var/runtime/index.mjs:1256:23)",
" at async file:///var/runtime/index.mjs:1262:1"
]
}
There are no logs present in the log viewer either.
This also functionally works in netlify dev
as expected.
No changes to the default nodejs version (which I believe is 18).
"type":"module"
is present in package.json.
Everything is ok locally. Please let me know how I can make this work please!
Can’t say much without seeing a reproduction. I have been able to import JSON files in Netlify Functions in the past without an issue. I did not have to specify assert
. Please share a minimal reproduction.
Working example:
sde.json
→ Place a json somewhere and reference it in the imports below
File: /functions/assert-example.js
// import sde from '../../frontend/src/generated-data/sde.json' // no assert is ok in netlify
import sde from '../../frontend/src/generated-data/sde.json' assert {type:'json'} // assert breaks netlify prod
export async function handler (event, context) {
return {
statusCode: 200,
body: JSON.stringify({ sde })
}
}
package.json
→ Contains type:'module'
netlify dev
→ Hit url http://localhost:8888/.netlify/functions/assert-example
→ Result ALL GOOD
netlify deploy --prod
→ Hit url https://abyssboard.netlify.app/.netlify/functions/assert-example
→ Result: Error:
ReferenceError - module is not defined in ES module scope This file is being treated as an ES module because it has a '.js' file extension and '/var/task/package.json' contains "type": "module". To treat it as a CommonJS script, rename it to use the '.cjs' file extension.
Renaming the file to .mjs
does seem to fix this, but I think the discrepancy between the netlify dev and prod behaviour should really be addressed.
Adding:
[functions]
node_bundler = "esbuild"
should fix it.