Skip to content

1. 安装导入

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

2. 直接import

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

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

3. 在html页面中导入

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

html
<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8" />
        <script type="module">
            import {Stage, Layer, Node, Link, jtopo} from './实际路径/jtopo.js';

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

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

4. 本地安装

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

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

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

代码中调用:

js
import {Stage, Layer, Node, Link, jtopo} from '@jtopo/core';
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/dist/index.js",
                    "@jtopo/editor": "../jtopo_npm/editor/dist/index.js"
                }
            }
        </script>

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

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

https://gitee.com/nengduan/jtopo_vue_vite

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