Skip to content

1. 安装导入

支持ES6语法,模块化采用标准规范:ESM, 下面是几种不同的导入方式:

2. 直接import

js
import {Stage, Layer, Node, Link, jtopo} from '@jtopo/core';

这种通常是采用了webpack、vite、rollup等构建工具的用法。

3. 在html页面中导入

3.1. 模块化导入

通过给 <script> 指定 type="module" 来导入:

html
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <script type="module">
            import {Stage, Layer, Node, Link} from './jtopo_npm/core/index.umd.js';

            // 示例:import {Stage, Node} from './jtopo_npm/core/index.umd.js';
            // let node = new Node();
            // ... 代码

       </script>
    </head>
    <body>
    </body>
</html>
  • 留意:路径是当前页面运行时浏览器能够访问到的路径,不是打包前的项目源码目录结构。

3.2. 传统引用方式

从v2.6.0版本开始提供umd格式,可采用传统js引用方式:

html
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <script src="./xxx/core/index.umd.js"></script>
        <script src="./xxx/extensions/index.umd.js"></script>
        <script>
            // 导入后,通过每个模块的全局变量来使用
            // core模块: JTOPO
            // extensions模块: JTOPO_EXTENSIONS
            // editor模块: JTOPO_EDITOR

            let stage = new JTOPO.Stage();
            let node = new JTOPO.Node("node", 0, 0, 32, 32);
            // ...

            let toobar = new JTOPO_EXTENSIONS.Toolbar();
            // ... 
       </script>
    </head>
    <body>
    </body>
</html>

4. 本地安装

npm 支持本地安装,假设我们提供的程序包解压后目录为: jtopo_npm, 将该目录放到项目的根目录下,安装:

sh
#安装 @jtopo/core
npm install ./jtopo_npm/core

#安装 @jtopo/extensions
npm install ./jtopo_npm/extensions

#安装 @jtopo/editor
npm install ./jtopo_npm/editor

代码中调用:

js
import {Stage, Layer, Node, Link} from '@jtopo/core';

import {Toolbar} from '@jtopo/extensions';

import {Editor} from '@jtopo/editor';

5. 浏览器中使用importmap导入:

目前流行的浏览器开始支持 importmap 的方式来配置路径了,如下: 
html
<!DOCTYPE html>
<html>
    <head>
         <meta charset="utf-8" />
        
         <!-- 在这里把运行时依赖的模块及路径事先配置好 -->
         <script type="importmap">
            {
                "imports": {
                    "@jtopo/core": "./jtopo_npm/core/index.js",
                    "@jtopo/editor": "./jtopo_npm/editor/index.js",
                    "@jtopo/extensions": "./jtopo_npm/extensions/index.js"
                }
            }
        </script>

        <script type="module">
            // from 后面不用写路径了,直接写模块名字
            import { Stage, Layer, Node, Link } from '@jtopo/core';
            // ... 代码
        </script>
    </head>
    <body>
    </body>
</html>
这种方式符合前端逐渐模块化的趋势,推荐!

6. 项目模板(Vue + vite + jtopo)

https://gitee.com/nengduan/jtopo_vue_vite

可以下载、参考学习、快速运行出第一个程序。