为什么es6导入作为空对象

时间:2017-07-14 20:25:45

标签: javascript node.js ecmascript-6 babeljs browserify

我正在制作一个Chrome插件。现在,我有“GetLink”类,它应该只是抓住活动选项卡DOM中出现的第一个链接。这是代码:

    export class GetLink {
        constructor() {
            chrome.tabs.query({'active': true, 'lastFocusedWindow': true}, tabs => {
                this.ajaxGet(
                    `${tabs[0].url}`,
                    data => this.getLink(data),
                    error => {throw new Error(`AJAX GET failed because response was ${error}`)}
                );
            });
        }

        ajaxGet(url, success, error) {
            if(!window.XMLHttpRequest) throw new Error(`This browser does not support XMLHttpRequest`);
            let request = new XMLHttpRequest();
            request.onreadystatechange = () => {
                if(request.readyState === 4) {
                    if(request.status !== 200) {
                        console.log(request.status)
                        if(error && typeof error === "function") {
                            error(error);
                        }
                    }
                    if(success && typeof success === "function") {
                        success(request.responseText);
                    }
                }
            };
            request.open("GET", url);
            request.send();
        }

        getLink(data) {
            let nodeList = document.createElement("html");
            nodeList.innerHTML = data;
            return nodeList.querySelector("a").href;
        }
    }
}

如果我删除导出并直接使用:

调用它,此功能可以正常工作
new GetLink()

但是当我尝试将其导入app.js(入口点)时,我得到一个空对象。 app.js与getLink.js位于同一目录中,并导入,分配,并将结果记录到控制台:

import {GetLink} from "./getLink";
let link = new GetLink();
console.log(`${JSON.stringify(link)}`); // outputs {} in the popup console

我正在使用npm脚本将其构建为缩小的,已编译的,浏览器安全的es5。这是包含相关脚本的package.json:

{
  "name": "getALink",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "browserify": {
    "transform": [["babelify", { "presets": ["es2015"] }]]
  },
  "devDependencies": {
    "jshint": "latest",
    "uglify-js": "latest",
    "babel-cli": "latest",
    "babel-preset-es2015": "latest",
    "babelify": "latest",
    "browserify": "latest",
    "watch": "latest"
  },
  "scripts": {
    "installClean": "rm -rf node_modules && npm install",
    "lint": "jshint src/scripts/app.js || true",
    "build": "mkdir -p app/js/ && browserify src/js/app.js -t [babelify --presets [es2015]] | uglifyjs -m -o app/js/app.min.js",
    "watch": "watch 'npm run build' src/"
  },
  "author": "HelloWorld",
  "license": "ISC"
}

我是否对import语句做错了?必须导出getLink.js,否则我会收到类型错误。也许我使用babel或browserify的方式有问题?

0 个答案:

没有答案