简体   繁体   中英

SyntaxError: Unexpected identifier with imported module Node.js

In my Node.js project I am trying to import a module of helper functions. I am getting this error:

/home/Projects/my_app/helpers.js:3
    var randomWeight = function(letters) {
        ^^^^^^^^^^^^ // <-- SyntaxError: Unexpected identifier with imported module Node.js
SyntaxError: Unexpected identifier

helpers.js:

module.exports = {

    function randomWeight (letters) {
        var total = letters.reduce(function (a, b) {
                        return a + b;
                    });
        var r = (Math.random() * (0 - total) + total.tofixed(5));
        var upto = 0;
        for (var i = 0; i<=letters.length; i++) {
            if ((upto + letters[i][0]) > r) {
                return letters[i][1];
            };
            upto += letters[i][0];
        };
    }

/routes/index.js:

var express = require('express');
var router = express.Router();
var logic = require('../logic.js');
console.log(logic.letterSet)

I have tried lots of different variations of the import statement, with result in the module being imported as an empty object. From searching SO it appears this is usually because of a circular import, but I am sure I'm not importing logic.js anywhere else in my project (specifically /server.js.) I am new to Node so troubleshooting this has been sort of like shooting in the dark.

EDIT:

I seem to have solved the problem by importing the appropriate functions individually, like:

exports.letterSet = letterSet;
exports.randomWeight = randomWeight; 

but I don't quite see how/why I can't import the whole module. I'm sorry if this seems like a ridiculous question but I am used to python where module imports are trivial.

you are returning an object {} in modules.exports, so you need to use object notation

module.exports = {

    randomWeight: function (letters) {
        var total = letters.reduce(function (a, b) {
                        return a + b;
                    });
        var r = (Math.random() * (0 - total) + total.tofixed(5));
        var upto = 0;
        for (var i = 0; i<=letters.length; i++) {
            if ((upto + letters[i][0]) > r) {
                return letters[i][1];
            };
            upto += letters[i][0];
        };
    }

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