Babel ES6 import error, SyntaxError: Unexpected token import
I am trying to set up a basic modular program, however I am having problems importing the modules. I am trying to import my custom module, I am getting the following error:
(function (exports, require, module, __filename, __dirname) { import testStep from 'testStep';
^^^^^^
SyntaxError: Unexpected token import
The code that is causing the problem:
testcase.js
import testStep from 'testStep';
testStep.hello();
testStep.js
var testStep = {
hello: hello,
};
var hello = () => {
console.log('hello world');
};
export default {testStep};
package.json
{
"name": "rebuild-poc",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"devDependencies": {
"babel-polyfill": "^6.23.0",
"babel-preset-env": "^1.6.0"
},
"dependencies": {}
}
.babelrc
{
"presets": [
"env"
]
}
I have already tried several other fixes such as setting testStep
as a class as well as using require('./testStep.js')
, however, none of them seemed to work.
Am I misconfigured something with babel or in one of my files?
*** Edit: I am running testCase.js
with node testCase.js
.
source to share
Please install babel-cli
and call your file with:./node_modules/.bin/babel-node testcase.js
It will fail. Now we need to fix your code.
testStep.js should look like this:
var hello = () => {
console.log('hello world');
};
var testStep = {
hello: hello,
};
export default testStep;
Then it will work. ;)
This is the first introduction at https://babeljs.io/ about what you should install babel-cli
and babel-preset-env
. ;)
You can also write your testStep.js like this:
var testStep = {
hello: hello,
};
function hello () {
console.log('hello world');
};
export default testStep;
It remembers the climb. As Jacob said in his first point.
source to share
-
You need to define
hello
withfunction
, usingvar
, you will not havefunction hoisting
, so when declaredtestStep
, ithello
will be undefined. -
If you want to use the es module, you can use
babel-register
orbabel-node
. In your code, node cannot handle the es module.
Babel-register
With bebel-register, your entire module will be handled by babel on import.
First yarn add babel-register babel-cli --dev
or npm install babel-register
babel-cli -dev
Then create a recording file:
// entry.js
require('babel-register')
require('testcase')
In your test script you can now use the es module.
Edit the package.json:
"scripts": {
"test": "node entry.js"
},
you can run yarn test
or npm run test
in terminal.
You don't need babel-polyfill
, that is, for browsers, not node.
source to share