sketch 导出与导入json文件

sketch 元素 转 json

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import { toSJSON } from 'sketch-json-helper';
import fs from "@skpm/fs";

const sketch = require('sketch')

// 导出json文件
export const exportJson = (context) => {
const document = sketch.fromNative(context.document);//声明
const selectedLayers = document.selectedLayers;

const arr = selectedLayers.layers;
const format = 'json'

if (arr.length === 0) sketch.UI.message("请选择要导出的组件!");
else if (arr.length > 1) sketch.UI.alert('提示', '只支持单选')
else {
arr.forEach(item => {
const savePanel = NSSavePanel.savePanel();
savePanel.setTitle('Save File');
savePanel.setNameFieldStringValue(item.name)
savePanel.setDirectoryURL(document.sketchObject.fileURL())
savePanel.setAllowedFileTypes([format]);

if (savePanel.runModal() === NSModalResponseOK) {
const url = savePanel.URL().URLByDeletingLastPathComponent().path();
const customFileName = savePanel.nameFieldStringValue()

fs.writeFileSync(`${url}/${customFileName}.${format}`, JSON.stringify(toSJSON(item)));
}
});

sketch.UI.message(`导出结束`);
}
};

sketch json 转 元素

1
2
3
4
5
6
7
import {fromNative} from 'sketch/dom';
import {toSJSON} from 'sketch-json-helper';

const nativeLayer = fromSJSON(json);
const sketchObj = fromNative(nativeLayer);
adjustFrame(sketchObj);
Document.getSelectedDocument().selectedPage.layers.push(sketchObj);