简体   繁体   中英

unusual unexpected token in webpack

I have a file call scripts.js and it merely do var main = require('./main');

and my main.js is at the same level, it has

module.exports = {
console.log("hello");
}

I do webpack in my terminal I got unexpected token?

You can not include function executions into a javascript object (you are exporting an object), you need to export a function to achieve this

module.exports = function() {
   console.log("hello");
}

And from your file where you require the export

var main = require('./main')(); // Add () to execute the function that you obtained

UPDATE:

You are executing console.log() in your main.js file, think that you can simply require some script without exporting nothing, and that file should be executed. For example you can put console.log("hello") without all the module.exports thing and the code should be executed, but when you check the value of your main variable (in the file where you do the require), you probably would not find anything useful.

You can also export a function(like in the code i send before) and then execute that function later, there's many ways to aproach this, I recommend you to google a bit about how module export works and how can you use it

You can check more about module.exports here https://www.sitepoint.com/understanding-module-exports-exports-node-js/ , you are using it for the browser, but this examples for node should be usefull anyways

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM