Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
13
rated 0 times [  14] [ 1]  / answers: 1 / hits: 26353  / 7 Years ago, tue, july 25, 2017, 12:00:00

I am trying to set up a basic modular program, however I seem to be running into issues with importing modules. I attempt to import my custom module, I get the following error:



(function (exports, require, module, __filename, __dirname) { import testStep from 'testStep';
^^^^^^
SyntaxError: Unexpected token import


The code that is causing the issue:



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 neither of those seem to have worked.



Do I have something set up incorrectly with babel or in one of my files?



***Edit: I am running testCase.js with node testCase.js.


More From » node.js

 Answers
33

Please install babel-cli and call your file with: ./node_modules/.bin/babel-node testcase.js



It will fail. Now we have to fix your code.



testStep.js should look like:



var hello = () => {
console.log('hello world');
};

var testStep = {
hello: hello,
};

export default testStep;


Then, it will work. ;)



This first introduction on https://babeljs.io/ is, that 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;


This keeps the hoisting in mind. Like Jacob said in his first point.


[#56988] Thursday, July 20, 2017, 7 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
stacie

Total Points: 476
Total Questions: 92
Total Answers: 102

Location: Bosnia and Herzegovina
Member since Tue, Mar 29, 2022
2 Years ago
stacie questions
Fri, Jun 26, 20, 00:00, 4 Years ago
Thu, Jan 23, 20, 00:00, 4 Years ago
Fri, Aug 30, 19, 00:00, 5 Years ago
Fri, Aug 2, 19, 00:00, 5 Years ago
;