i can see that the error:
SyntaxError: Cannot use import statement outside a module
has a solution posted here:
https://stackoverflow.com/a/70031461
which is basically to either:
- add
"type": "module"to yourpackage.jsonfile - add the
.mjsextension to your middleware file
however, i am using babel to transpile server-side node/express.js code.
it was my understanding that babel transpiles import/export statements to relevant require/module.exports statements.
to clarify, i am only getting this error after i have extracted the import statement to a separate middleware file.
previously i had this in app.js and the application worked with no errors:
import { format } from 'date-fns';
however, now that i have extracted that statement into a middleware file, i am getting the error:
SyntaxError: Cannot use import statement outside a module
package.json
"build-server-file": "babel app_before_babel.js --out-file app.js",
// ...
"devDependencies": {
"@babel/cli": "^7.16.0",
"@babel/core": "^7.16.0",
"@babel/preset-env": "^7.16.0",
"babel-loader": "^8.2.3",
// ...
.babelrc.json
{
"presets": [
[
"@babel/preset-env",
{
"targets":
{
"node": "current"
}
}
]
]
}
my_middleware_file.js
import { format } from 'date-fns';
const current_date_time_to_iso_string = () => {
var iso_string = parseISO(new Date().toISOString());
return iso_string;
};
export { current_date_time_to_iso_string };
date-fns website
environment
node -v
v16.13.0
npm -v
8.1.4
Edit:
I just tried adding an export statement to another file i am trying to import into a middleware file, and am getting the error:
SyntaxError: Unexpected token 'export'
So perhaps babel is not transpiling any of the files external to the main app.js file?
The application structure is essentially:
app.js <---- entry file
routes
- index.js
- resource_01_route.js
- resource_02_route.js
- resource_03_route.js
// etc
middleware
- middleware_01.js
- middleware_02.js
- middleware_03.js
// etc
views
- index.ntl
config
- db_connection.js
- environment_variables.js
- local_settings.js
All route files will import middleware files.
middleware files will import files in /node_modules, other middleware files and config files.
Do I need to somehow configure babel to understand this directive:
transpile everything that is imported in this project, except for things in
/node_modules?
It seems this issue was discussed here back in 2018, but i can't understand what the solution is.