admin管理员组文章数量:1125896
I am trying to run some ES6 code in my project but I am getting an unexpected token export error.
export class MyClass {
constructor() {
console.log("es6");
}
}
I am trying to run some ES6 code in my project but I am getting an unexpected token export error.
export class MyClass {
constructor() {
console.log("es6");
}
}
Share
Improve this question
edited Jul 11, 2016 at 7:32
str
44.9k17 gold badges114 silver badges134 bronze badges
asked Jul 10, 2016 at 21:35
JasonJason
5,7472 gold badges11 silver badges3 bronze badges
3
|
20 Answers
Reset to default 552Updated for 2022
You are using EcmaScript Module (ESM or 'ES6 Modules') syntax but your environment does not support it.
NodeJS versions prior to v14.13.0 do not support ESM (export
keyword syntax) and use CommonJS Modules (module.exports
property syntax). NodeJS v14.13.0 and newer supports ESM but it must be enabled first.
Solutions:
- If you are using NodeJS v14.13.0 or newer (which does support ESM) you can enable it by setting
"type":"module"
in your projectpackage.json
- Refactor with CommonJS Module syntax (for older versions of NodeJS)
- Consider using TypeScript alongside
ts-node
orts-node-dev
npm packages (for instant transpilation at development time) and write TypeScript in.ts
files - Transpile ESM to CommonJS using esbuild (
esbuild
package on npm) configured to transpile your ES6 javascript to a CommonJS target supported by your environment. (babel is no longer recommended)
In case you get this error, it might also be related to how you included the JavaScript file into your html page. When loading modules, you have to explicitly declare those files as such. Here's an example:
//module.js:
function foo(){
return "foo";
}
var bar = "bar";
export { foo, bar };
When you include the script like this:
<script src="module.js"></script>
You will get the error:
Uncaught SyntaxError: Unexpected token export
You need to include the file with a type attribute set to "module":
<script type="module" src="module.js"></script>
then it should work as expected and you are ready to import your module in another module:
import { foo, bar } from "./module.js";
console.log( foo() );
console.log( bar );
My two cents
Export
ES6
myClass.js
export class MyClass1 {
}
export class MyClass2 {
}
other.js
import { MyClass1, MyClass2 } from './myClass';
CommonJS Alternative
myClass.js
class MyClass1 {
}
class MyClass2 {
}
module.exports = { MyClass1, MyClass2 }
// or
// exports = { MyClass1, MyClass2 };
other.js
const { MyClass1, MyClass2 } = require('./myClass');
Export Default
ES6
myClass.js
export default class MyClass {
}
other.js
import MyClass from './myClass';
CommonJS Alternative
myClass.js
module.exports = class MyClass1 {
}
other.js
const MyClass = require('./myClass');
There is no need to use Babel at this moment (JS has become very powerful) when you can simply use the default JavaScript module exports. Check full tutorial
Message.js
module.exports = 'Hello world';
app.js
var msg = require('./Messages.js');
console.log(msg); // Hello World
I fixed this by making an entry point file like.
// index.js
require = require('esm')(module)
module.exports = require('./app.js')
and any file I imported inside app.js
and beyond worked with imports/exports
now you just run it like node index.js
Note: if app.js
uses export default
, this becomes require('./app.js').default
when using the entry point file.
To use ES6 add babel-preset-env
and in your .babelrc
:
{
"presets": ["@babel/preset-env"]
}
Answer updated thanks to @ghanbari comment to apply babel 7.
Install the babel packages @babel/core
and @babel/preset
which will convert ES6 to a commonjs target as node js doesn't understand ES6 targets directly
npm install --save-dev @babel/core @babel/preset-env
Then you need to create one configuration file with name .babelrc
in your project's root directory and add this code there.
{ "presets": ["@babel/preset-env"] }
Just use tsx
as your runtime instead of node
. It will allow you to use normal import statements, without switching your project to type: module
and without having to deal with the nasty consequences of type: module
. In addition, you'll get TypeScript support.
I had modules working for a while, and then they weren't with this Uncaught SyntaxError: Unexpected token export
error.
Turns out, I had added an open brace without a closed brace. Something like:
if (true) {
/* } missing here */
export function foo() {}
While the big error is the forgetting of the end }
, the parser first finds an export inside the brace, which is a no-no.
The export
keyword must be in the top level of the file.
So:
if (true) {
export function foo() {}
}
would also be illegal. When the parser encounters this, it stops parsing right there, announcing the misuse of export
vaguely, giving the same error it gives when it is loading a "non-module" JavaScript file that uses the export
keyword. It never reports the underlying missing brace error.
Took me a long time to figure that out, so I'm posting here to help any future sufferers.
Ideally, the parser would report that export
is only allowed at the top level of the file.
Got through this problem: browsers only support the ES syntax and do not understand require
and exports
as used in CommonJS. The problem arises from importing files that have the .ts
extension.
To solve this use the ES6 module import in your files.
Example: Folder Structure
dist
src
|-app.ts
|-components
|-button.ts
|-helper
|-eventHander.ts
tsconfig.json
index.html
- In the tsconfig file, set
"module": "ES2015"
- In the tsconfig file, set
"outDir": "./dist"
- In the HTML file add the attribute
<script type="module" src="./dist/app.js"></script>
You can read more about modules here: JavaScript modules
- The eventHander.ts file
type Handler<T> = (e: T) => void;
const eventHander: Handler<Event> = (e: Event) => {
e.preventDefault();
alert("You Clicked");
};
export default eventHander;
- In the button.ts
import eventHander from "../helper/eventHander.js"
function createButton(): HTMLElement {
let button: HTMLElement;
button = document.createElement("button");
button.addEventListener("click", eventHander);
button.innerText = "Click Me"
return button
}
export default createButton
- In the app.ts file
import createButton from "./components/button.js";
const hostElement: HTMLElement = document.getElementById("app")!;
hostElement.insertAdjacentElement("beforeend", createButton());
Your HTML code should be like this:
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div id="app"></div>
</body>
<script type="module" src="./dist/app.js"></script>
I experienced this problem and it took me an hour to find my problem.
The problem was that I was changing my code from non-modules to modules and I forgot to delete the imported script file.
My "table.js" file had the following line. This is the module file.
export function tableize(tableIdentifier) {
My "orderinquiry.js" file had the following line.
import { tableize, changeColumnSizesDynamic } from '../common/table.js';
My "orderinquiry.html" had the following two lines.
<script src='/resources/js/common/table.js'></script>
<script type='module' src='/resources/js/client/orderinquiry.js'></script>
While the second line is good and declares type='module
. But the first line directly links to table.js and caused the unexpected error. Everything started working when I removed that first <script>
.
For those that are viewing this in 2022, I had the same error, however I changed my code to something like this:
module.exports = () => {
getUsers: () => users;
addUser: (user) => users.push(user);
};
Normally import not working in a .js extension because by default js means cjs version of javascript. If you want to es6 feature you need to rename the .js extension to the .mjs extension
parent.mjs
export default class Car {
constructor(brand) {
this.carname = brand;
}
present() {
return 'I have a ' + this.carname;
}
}
child.mjs
import Car from './parent.mjs'
export default class Model extends Car {
constructor(brand, mod , country) {
super(brand);
this.model = mod;
this.country = country;
}
show() {
return this.present() + ', it is a ' + this.model + "i am from " +
this.country;
}
}
index.html
<!DOCTYPE html>
<html lang="en" class="no-js">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0,
shrink-to-fit=no">
<title>Quick Start Pack Template</title>
</head>
<div class="demo"></div>
<script type="module">
import Model from './child.mjs'
let value = new Model("Ford", "Mustang", "bangladesh")
document.querySelector(".demo").innerHTML = value.show()
</script>
</body>
</html>
Finally run this code on live server
Another way to import ES6 module from CommonJS
is to rename your ES6 module file to have .mjs
extension. This is one way for backward compatibility. Then in your CommonJS code, you can import like this:
Top of file import:
import myClass from "./MyClass.mjs"
or Dynamic Import anywhere in the code:
const myClass = await import("./MyClass.mjs");
Note that your CommonJS
file does not need to be renamed to .mjs
. More info here.
it is a simple common error sometimes... When we import into the plain Vanilla JS module a ./file instead of a ./file.js (especially when the import is generated by IntelliJ). It has happened to me several times, please consider this, too!
I got the unexpected token export error also when I was trying to import a local javascript module in my project. I solved it by declaring a type as a module when adding a script tag in my index.html file.
<script src = "./path/to/the/module/" type = "module"></script>
In the latest versions of Nodejs (v17?) you can use top-level "import", "async", "await" by using the .mjs file extension - instead of transpiling or workarounds.
// > node my.mjs
import {MyClass} from 'https://someurl'
async func () {
// return some promise
}
await func ()
Using ES6 syntax does not work in node, unfortunately, you have to have babel apparently to make the compiler understand syntax such as export or import.
npm install babel-cli --save
Now we need to create a .babelrc file, in the babelrc file, we’ll set babel to use the es2015 preset we installed as its preset when compiling to ES5.
At the root of our app, we’ll create a .babelrc file. $ npm install babel-preset-es2015 --save
At the root of our app, we’ll create a .babelrc file.
{ "presets": ["es2015"] }
Hope it works ... :)
// ✅ Using module.exports instead of export module.exports = { Person, };
I actually want to add simple solution. use const
and backticks(`).
const model = `<script type="module" src="/"></<script>`
本文标签: javascriptGetting Unexpected Token ExportStack Overflow
版权声明:本文标题:javascript - Getting Unexpected Token Export - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1736678748a1947317.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
export
is only available in ES6, and those modules are what provide ES6 support. – Claies Commented Jul 10, 2016 at 21:44module.exports = MyClass
, notexport class MyClass
– onmyway133 Commented Aug 4, 2017 at 9:47mjs
extension should tell Node you're using ES6 Module syntax. – Yair Kukielka Commented Oct 27, 2021 at 7:23