5

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>
Ijas
  • 367
  • 1
  • 3
  • 18

1 Answers1

4

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.

theDavidBarton
  • 7,643
  • 4
  • 24
  • 51
  • I have tried this but log is not showing in the browser logs. why logs are showing in terminal? – Ijas Jul 01 '20 at 08:04
  • If you want to use these JavaScript functions on the client side and not the server side (electron), then you need to add the ".js" ending in your import `import { sample } from './eventhandler.js'` and it will console.log to the brwoser's console. – theDavidBarton Jul 01 '20 at 09:34
  • Inside the HTML with electron you have to use require. Most of the cases the solution is: `webPreferences: { nodeIntegration: true }` [link](https://stackoverflow.com/a/55908510/12412595). But it is considered as a security risk. Here is a secure description how to do that properly: https://github.com/electron/electron/issues/9920#issuecomment-575839738 – theDavidBarton Jul 01 '20 at 10:20