Javascript unexpected token export

Javascript unexpected token export

Here’s an example of how the error occurs in a Node.js application.

Copied!
// ⛔️ Uncaught SyntaxError: Unexpected token 'export' export class Person constructor(first) this.first = first; > >

# Set the type property to module in your package.json file

To solve the error, set the type property to module in your package.json file.

Files ending with a .js extension are loaded as ES6 modules when the nearest package.json has a type field set to module .

If you don’t have a package.json file, you can create one with the npm init -y command.

Open your terminal in your project’s root directory and run the following command.

Now set the type property to module in the package.json file:

Copied!
"type": "module", // . rest >

Now you can use the ES6 modules import/export syntax in your Node.js application.

This is a file called index.js that has 2 named exports.

Copied!
// 👇️ named export export class Person constructor(first) this.first = first; > > // 👇️ named export export const site = 'bobbyhadz.com';

And here’s how we would import the class and variable into a file called another-file.js .

Copied!
import Person, site> from './index.js'; const p1 = new Person('James'); console.log(p1); // 👉️ Person console.log(site); // 👉️ bobbyhadz.com

Make sure to specify the extension of the file in your import statements.

Setting the type property to module in the package.json file of your project allows you to use ES6 modules in your Node.js application.

# Using the older CommonJS syntax instead

If you don’t want to set the type property to module in your package.json , you can use the older CommonJS syntax.

You can also solve the error by refactoring your code to use the CommonJS syntax, e.g. module.exports = ; instead of export num = 10; .

Copied!
class Person constructor(first) this.first = first; > > // ✅ Using module.exports instead of export module.exports = Person, >;

Then we can import members of other files using require() .

Copied!
const Person> = require('./index.js');

Make sure that you haven’t set the type attribute to module in your package.json file and you don’t have files with a .mjs extension to be able to use the require() syntax.

The error occurs because we aren’t allowed to use the ES6 Modules import/export syntax in Node.js yet.

There are multiple ways around it, e.g. to use babel to transpile our ES6 code to an older version of JavaScript, or simply refactor our code to the CommonJS syntax.

# Uncaught SyntaxError Unexpected token ‘export’ in Browser

To solve the error, set the type of your tags to module .

The type=»module» attribute is supported in all modern browsers and allows us to use the ES6 modules syntax.

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> head> body> script type="module" src="index.js"> script> body> html>

Setting type to module enables us to use the ES6 modules syntax in the index.js file.

Copied!
// 👇️ named export export class Person constructor(first) this.first = first; > > // 👇️ named export export const site = 'bobbyhadz.com';

As long as you use set the type attribute to module when loading your scripts, you can use the ES6 modules syntax.

You can then import the exports in the following way.

Copied!
// 👇️ named imports import Person, site> from './index.js'; console.log(Person); // 👉️ [class Person] console.log(site); // 👉️ "bobbyhadz.com"

Note that you have to set the type attribute to module on all scripts that use the ES Modules syntax.

Copied!
DOCTYPE html> html lang="en"> head> meta charset="UTF-8" /> head> body> script type="module" src="index.js"> script> script type="module" src="another-file.js"> script> body> html>

Источник

Fixing SyntaxError Unexpected Token ‘export’

Having issues with the error SyntaxError Unexpected Token ‘export’. This post list ways to get rid of that!

Jan 21, 2023 | Read time 10 minutes

🔔 Table of contents

Introduction

A common issue that comes up when I was working with single page apps with frameworks like Vue or React is the error: SyntaxError Unexpected Token ‘export’

frusted web developer with this syntax error unexpected token export

The export keyword is from EcmaScript Module (ESM or ‘ES6 Modules’) standard. The error SyntaxError Unexpected Token ‘export’ comes up in your code because the environment that the code runs on does not support it. This can be front-end code (eg browser) or from a backend (Node JS)

Specifically, the “syntaxerror unexpected token ‘export’» error is caused by any one of the following:

  • In HTML, not setting the type attribute to equal module on the script tag —
  • Not using the latest version of Node that supports ES6 standard

In this article, I will go over steps to address this error! Use the following checklist to fix the “syntaxerror unexpected token ‘export’” error in JavaScript:

Check browser support for ES6. The “export” keyword is part of the ECMAScript 6 (ES6) standard so make sure that browser will support this version!

Check the correct syntax — use the type=»module» attribute in HTML

Make sure you are not mixing CommonJs module with the export keyword

What is the export keyword anyway?

The export keyword allows you to make variables, functions, and objects available for use in other parts of your code by allowing them to be imported using the import keyword.

A simple way to use export is as follows — consider we have a Javascript file named moduleX.js:

Now, we have another file called index.js and we want to use the variables from the moduleX.js file, we just use it with the import keyword.

So in our index.js file, we can have the following code:

1. Check browser support for ES6

ECMAScript 6 (ES6) is the sixth major release of the ECMAScript language specification. It was finalized in June 2015! It came with a bunch of improvements including the export and import keywords.

This forms the base for the modules functionality — providing a way to organize and reuse JavaScript code (previouly done through CommonJS)

However there are limitations on the support. Theres pretty much no support for ES6 functionality on IE11 or lower

2. Check the correct syntax — use the type=»module» attribute in HTML

Consider the following module.js javascript file — we will get the “Uncaught SyntaxError: Unexpected token export” when we don’t include the type=module attribute:

Now if we include that in our HTML - the error will appear:
 We can also use the import keyword to use that module.js file ( ):

I found this error can come up when our module JavaScript library got syntax errors. As an example below, we get a missing curly closing bracket:

3. Make sure you are not mixing CommonJs module with the export keyword

One common confusion when using the export keyword is mix and matching it with CommonJS

If we run the above, we can see:
Now if we are using CommonJS, we should not mix it with the export keyword - we should use the export object (confusing right? :P)

To fix the above code, we just replace the export keyword with module.export — so our final code looks like this:

Before ES6 and exports keyword, CommonJS is a project proposes a module system for JavaScript. This enables developers to organize their code into reusable modules and manage dependencies between them.

Its usually used in NodeJS projects with the module.exports object to export things like functions, variables, etc. To use the exports we just use the require() function.

An example of how to use it is below:

Then we have another file — index.js which uses the math.js file:

4. For server-side JavaScript — verify the Node version supports ES6

Support for ES6 and the export keyword syntax (ESM) is only available in NodeJS v14.13.0.

Previously before NodeJS version 14.13.0, CommonJS modules are used — module.exports property syntax and require()

Some possible solutions:

  • Upgrade to the latest version of Node which supports the export keyword syntax. If you are using NodeJS v14.13.0 or newer (which does support ESM) you can enable it by setting “type”:“module” in your project package.json
  • Refactor with CommonJS Module syntax (for older versions of NodeJS)
  • Transpile the export keyword syntax to CommonJS using esbuild NPM package. This can be configured to transpile your ES6 javascript to a CommonJS pattern.
  • Use babel to transpile your code to ES6.

Fixes for Syntax error unexpected token ‘export’ for Express

A few common reasons why this error comes up in NodeJs or Express:

  • You are using a old version of Node — make sure to use versions v14.13.0 or above so that ES6 features such as export/import are supported.
  • You are mixing CommonJS (using require()) with the export keyword!

Tips for fixing React/Jest Syntax error Unexpected token ‘export’ — transformIgnorePatterns

This error comes up in React projects when we run the Jest testing framework with React.

As an example below, previously I had a React app and decided to install DeckGl (https://github.com/visgl/deck.gl)

Then after install I got this lovely error when trying to run the test suite with Jest:

Test suite failed to run /my_project/node_modules/deck.gl/src/react/index.js:21  To fix this we just need to update the jest.config.js file with the following configuration:

By default Jest doesn’t transform node_modules, because they should be valid JavaScript files. In our case DeckGL is written with ES6 therefore leading to syntax errors. So you have to tell this to Jest explicitly transform it:

 The above code just means that DeckGL will be transformed, even though they are node_modules.

Consideration for NextJS similar errors — next-transpile-modules

Consider using the next-transpile-modules package when you see this error in your NextJS projects.

In the below scenario, I tried to add react-icons to my NextJs project but when you build — it gives the error!.

  1. In your next.config.js file add the line const transpiledModules = require(‘next-transpile-modules’)([«react-icons»]);

Replace react-icons with whatever package is failing for you.

The reason for this is the react-icons package exports a function using ES6 import/export module. This fails in the browser since it does not know ES6 syntax and spits out Syntax error Unexpected token ‘export’

NextJs by default only transpiles code in the src folder and not in the node_modules folder. This is why we need the next-transpile-modules package to transpile the dependency in node_modules from ES6!

Summary

Modules are a step up in managing large JavaScript codebases, however some of the errors that it spits out can be confusing.

This post I went over the annoying syntax unexpected token errors when working with modules in JavaScript. The reason for Uncaught Syntax error Unexpected token ‘export’ error is mainly due to: — not using the the type=module , using old versions of Node, running the JavaScript module code in a browser that does not support ES6, and mixing and matching with CommonJS require() and the new export/import keywords!

👋 About the Author

G’day! I am Kentaro a software engineer based in Australia. I have been creating design-centered software for the last 10 years both professionally and as a passion.

My aim to share what I have learnt with you! (and to help me remember 😅)

👉 See Also 👈

Источник

Читайте также:  Зачем нужен super python
Оцените статью