未捕获到的SyntaxError:Chrome中出现意外令牌{

时间:2018-10-14 10:30:43

标签: javascript google-chrome closures

我正在尝试使用javaScript中的导入和导出连接三个文件rule.jsevent.jsaction.js

event.js中的函数将从浏览器获取数据,当and条件满足时,它将从rule.js运行该函数,然后执行该操作。

// rule.js

import{actionOne} from 'action.js';
var scrollAndTime = (function(){
    return function(){
        console.log(actionOne());
    }
})();

export{scrollAndTime};

// event.js

import { scrollAndTime } from 'rule';

var scrollPercentage = (function(){
    var scrollRun = false;  // This is for future use
    if(!scrollRun){
        return function(scroll){
            console.log("I am Scroll.");
            var height = document.documentElement,
                body   = document.body,
                st     = 'scrollTop',
                sh     = 'scrollHeight';
                scrollRun = scroll;
            var scrollPercent = (height[st]||body[st]) / ((height[sh]||body[sh]) - height.clientHeight) * 100;
            return scrollPercent;
        }
    }
})();

var timeSpent = (function(){
    var time    = new Date();
    var timeRun = false,  // This is for future use
        startTime = time.getTime();
    if(!timeRun){
        return function(){ // call this function by timeSpent()(); 
            console.log("I am Time.");
            return (new Date()).getTime() - startTime;
        }
    }
})();


// Handling and condition between scrollPercentage and timeSpent
var and=false;

addEventListener("click",function(){
    if(!and){
        var scrollAndTimeSpent=false;
        if(scrollPercentage()>70 && timeSpent()>15000){
            // this.alert("Executed!");
            and=true;
            scrollAndTimeSpent=true;
        }
        if(scrollAndTimeSpent){
            // Tell rule engine that I have completed
            // Execute this function.
            scrollAndTime();
        }
    }
})

// action.js

var actionOne = (function(){
    return function(){
        // Do the following things and return the required thing.
        return "ActionOne done!";
    }
})();

export{actionOne};

// index.html-这是使用这些js文件的页面。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">
    <link rel="stylesheet" href="main.css">
    <title>Rule Engine</title>
</head>
<body>
    <script type="module" src="event.mjs"></script>
</body>
</html>

现在当我使用type =“ module”时,我得到 (CORS策略禁止从源“ null”访问“ file:///Users/praveenkumarrana/Desktop/Projects/ruleengine/event.mjs”处的脚本:响应无效。因此,不允许访问源“ null”。 ) 错误。

当我不使用它时,会出现(Uncaught SyntaxError: Unexpected token { in Chrome.)错误。

1 个答案:

答案 0 :(得分:0)

从这一行开始,

  

file:///Users/praveenkumarrana/Desktop/Projects/ruleengine/event.mjs

我假设您正在文件系统中运行此代码(不通过本地服务器)。 由于ES6模块容易受到同源策略的限制,因此如果没有CORS标头,则无法从文件系统或跨域导入它们。本质上,您必须从服务器运行此代码在浏览器中禁用同源(用于测试)