how to use import or require in electron

Viewed 4289

I'm trying to build an electron app. I want to import some functions from another js files. but while using import i gets error showing

cannot use import statement outside a module why this happening

my code is eventsource.js

import { sample } from './eventhandler'
console.log('inside eventsource');
function test(){
console.log('test function')
}
test();
sample();

eventhandler.js

export function sample(){
console.log('sample')}

prototype.html

<!DOCTYPE html>
<html>
<head>
<meta charset = "UTF-8">
<title>sample</title>
<script type="module" src="../views/eventsource.js"></script>
</head>
<body class="content">
</body>
</html>
1 Answers

As the error msg says you are unable to use ES6 imports in Node.js. You should go for require and module.exports

const { sample } = require('./eventhandler');
console.log('inside eventsource');
function test() {
  console.log('test function');
}
test();
sample();
function sample() {
  console.log('sample');
}

module.exports.sample = sample

For ES6 export/import you need experimental support for the feature. Read more about this on Node.Js's site.

Related