Home > front end >  I am trying to use import and export in javascript but it is showing uncaught error. Here is the cod
I am trying to use import and export in javascript but it is showing uncaught error. Here is the cod

Time:04-09

my code :

const person = {
    name: 'Aish',
    age:21,
}

export default person;

error : Uncaught SyntaxError: Unexpected token 'export' (at main.js:6:1)

CodePudding user response:

Change script extensions to .mjs, or add an entry to package.json: "type" : "module" .

*Node.js fully supports ECMAScript modules as they are currently specified and provides interoperability between them and its original module format, CommonJS.

Enabling#
Node.js has two module systems: CommonJS modules and ECMAScript modules.

Authors can tell Node.js to use the ECMAScript modules loader via the .mjs file extension, the package.json "type" field, or the --input-type flag. Outside of those cases, Node.js will use the CommonJS module loader. See Determining module system for more details.**

Source

CodePudding user response:

This is because you're using ES6 import/export but the environment you're working on is using commonjs

for Node.js

go to your package.json and set the type entry as "module"

example:

{
  "name": "test",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "type": "module",
  ...
}

Note: make sure to update your nodejs to latest version

for Browser

in your script tag add type='module' as an attribute

example:

<script src="./index.js" type="module" defer></script>
  • Related