0

我正在研究将 ES6 导入/导出添加到Transcrypt Python to JavaScript 编译器。作为为此目的的实验,我有以下代码:

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />            
        <script type="module" src="testmodule.js"></script> 
        <script type="module" src="testmain.js"></script>
    </head>
    <body>
    </body>
</html>

和 testmodule.js:

'use strict';

function testmodule_f () {
    function cube(x) {
      return x * x * x;
    }
    const foo = Math.PI + Math.SQRT2;
    var graph = {
        options:{
            color:'white',
            thickness:'2px'
        },
        draw: function(){
            console.log('From graph draw function');
        }
    }
    var all = {cube, foo, graph};
    return all;
}

var testmodule = testmodule_f ();

export {testmodule as default};

和 testmain.js:

'use strict';

import {tm} from './testmodule.js';
tm.graph.options = {
    color:'blue',
    thickness:'3px'
}; 
tm.graph.draw();
console.log(tm.cube(3)); // 27
console.log(tm.foo);    // 4.555806215962888

我得到:

Uncaught SyntaxError: The requested module does not provide an export named 'tm'

使用正常的命名导出(因此没有默认值)它可以正常工作。我究竟做错了什么?

此外,如果我将 testmain.js 更改为以下内容,则它可以工作:

'use strict';
import {default as tm} from './testmodule.js';
tm.graph.options = {
    color:'blue',
    thickness:'3px'
}; 
tm.graph.draw();
console.log(tm.cube(3)); // 27
console.log(tm.foo);    // 4.555806215962888

似乎 Chrome 对这个词没有做任何事情default,除了把它当作一个完全普通的名字吗?但这与以下内容相矛盾:

https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import

4

1 回答 1

0

以下作品:

testmain.js

'use strict';
import tm from './testmodule.js';
tm.graph.options = {
    color:'blue',
    thickness:'3px'
}; 
tm.graph.draw();
console.log(tm.cube(3)); // 27
console.log(tm.foo);    // 4.555806215962888

测试模块.js

'use strict';

function testmodule_f () {
    function cube(x) {
      return x * x * x;
    }
    const foo = Math.PI + Math.SQRT2;
    var graph = {
        options:{
            color:'white',
            thickness:'2px'
        },
        draw: function(){
            console.log('From graph draw function');
        }
    }
    var all = {cube, foo, graph};
    return all;
}

var testmodule = testmodule_f ();

export default testmodule;

仍然我的印象是原始代码也应该工作......

于 2018-03-09T10:23:40.283 回答