I have a vanilla Express app whose package.json looks like this:
{
"name": "express-app",
"version": "1.0.0",
"main": "app.js",
"dependencies": {
...
},
"devDependencies": {
...
},
"scripts": {
...
},
}
And I want to write a script outside the express app that imports a module from the express app. The module resides in ./src/model/Example.js
That module also imports various other modules.
The script is located at ./scripts/test.mjs
and does:
import Example from '../src/models/Example.js';
However, I'm getting this hitting the first import from Example.js
:
SyntaxError: Cannot use import statement outside a module
How do I structure this such that the script can import the module correctly?
The "SyntaxError: Cannot use import statement outside a module" occurs when we use the ES6 Modules syntax in a script that was not loaded as a module. To solve the error, set the type attribute to module when loading a script, or in your package. json for Node. js apps.
The reason for this error is that Node js doesn't support ES6 import directly. If you try to use import for importing modules directly in node js it will throw out that error. Do not worry about the error!
You can import modules into a file in two ways, based on if they are named exports or default exports. Named exports are constructed using curly braces. Default exports are not.
It is because your project in vanilla JS, the import statement is not going to work. You can use parceljs a zero config package bundler which supports ES6 and above syntax to use it first add it as a dev dependency by running
npm install parcel-bundler --save-dev
And then add to scripts to your package
{
"scripts": {
"dev": "parcel <your entry file>",
"build": "parcel build <your entry file>"
}
}
replace the entry file with your main file in your code (example: app.js
)
did you try
const Example = require('../src/models/Example.js')
The modern way to do that is on yow package.json Add a property call type and set the value of module
{
“name”;”project name”,
…
“type”;”module”,
…
“dependencies”:”….”,
}
by default nodejs treads yow code as
type: commons
It is why it says you cannot use import out side a module, bcuz yow package.json implicitly marks yow codes as type commonjs.
So after you set type module then you need to change the extension of them JavaScript files, from .js to .mjs
. Yes you guessed right the m is from module.
You can do this or configure Babel, webpack, while you find the holy grail and what ever else is need it
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With