首页 > 解决方案 > 尝试对未通过 npm 安装的库使用 ES2015 模块系统

问题描述

因此,我有几个用于自定义 Web sdk 的依赖库,我正在尝试启动并运行它们。

这些库位于我调用的根文件夹中modules/,这就是我将它们包含在 HTML 文件中的方式:

<script type="module" src="modules/xm/js-es6/xmsdk-es6.js"></script>

这就是我将它导入index.js文件的方式:

import { XmSdk } from './modules/xm/js-es6/xmsdk-es6';

为此我得到错误:Cannot use import statement outside a module.

我认为添加标签就type="module"足以<script>解决这个问题,但坦率地说,我从未使用过未node_modules/安装的 ES2015 模块系统。

下面是index.html我在index.js下面的脚本标记中加载文件的文件:

<html>
    <head>
       
            <link rel="stylesheet" type="text/css" href="modules/xm/css/xmui.css">
            <link rel="stylesheet" type="text/css" href="app.css">
            <!-- SDK's CORE API module -->
            <!-- <script type="module" src="modules/xm/js-es6/xmsdk-es6.js"></script> -->
            <!-- SDK's Default UI Handler module  -->
            <!-- <script type="module" src="modules/xm/js-es6/xmui-es6.js"></script>  -->
            <script src="js/ext/require.js"></script>
            <script>
                requirejs.config({
                    baseUrl: '',
                    paths: {
                        XmSdk: '/xmwl/xm/js-es6/xmsdk-es6',
                        XmUIHandler: '/xmwl/xm/js-es6/xmui-es6'
                    }
                });
            </script>
        
        <!-- SDK's CORE API module -->
        <!-- <script type="module" src="modules/xm/js/xmsdk.js"></script> -->
        <!-- SDK's Default UI Handler module  -->
        <!-- <script type="module" src="modules/xm/js/xmui.js"></script>   -->
    </head>
    <body>
    <div>
        <label for="username">Username:</label>
        <input id="username" type="text"/><br>
        <!-- <label for="password">Password:</label>
        <input id="password" type="text"/><br> -->
        <button id="loginButton" type="button">Login</button> 
        <button id="logoutButton" type="button">Logout</button>
        <br>
        <div class="transmitContainer"></div>
    </div>
    
    <form id="resumeAuthForm" style="display:none" method="post" action="logout.html">
        <input type="hidden" id="resumeAuthFormToken" name="xm_auth_token"/>
        <input type="hidden" id="resumeAuthFormUsername" name="user_name"/>
    </form>
        <!-- <script>
            require(['XmSdk', 'XmUIHandler'], (xmsdk, xmui) => {
 
            });
        </script> -->
        <script src="index.js"></script>
    </body>
</html>

标签: ecmascript-6

解决方案


仅使用元素将入口点加载到程序中。<script>用于type="module"将其标记为 ES6 模块(只有模块可以导入其他模块):

<script src="index.js" type="module"></script>

不要<script>使用元素加载其他模块。

<script type="module" src="modules/xm/js-es6/xmsdk-es6.js"></script>替换为 import { XmSdk } from './modules/xm/js-es6/xmsdk-es6';


推荐阅读