0.1.7 • Published 2 years ago

san-sfc-compiler v0.1.7

Weekly downloads
-
License
MIT
Repository
github
Last release
2 years ago

san-sfc-compiler

Lower level utilities for compiling .san single file components

fork from vuejs/component-compiler-utils

API

parseSFC

描述:解析 .san 文件源码

使用:

parseSFC({
  source: '<div><p>{{ helloworld }}</p></div>',
  filename: 'test.san',
});

// 选项
export interface ParseOptions {
  source: string;
  filename?: string;
  sourceRoot?: string;
  needMap?: boolean;
}

方法 / 属性:

方法 / 属性描述类型
source源码string
filename文件名string
sourceRootsourcemap 选项string
needMapsourcemap 开关(template 没有boolean

返回:

export interface SFCDescriptor {
  template: SFCBlock | null;
  script: SFCBlock | null;
  styles: SFCBlock[];
  customBlocks: SFCBlock[];
}

其中 SFCBlock 类型为这样:

{
    type!: string;
    content!: string;
    attrs!: Record<string, string | true>;
    start!: number;
    end!: number;
    lang?: string;
    src?: string;
    scoped?: true;
    module?: string | true;
}

content 就是标签内容了。

compileTemplate

描述:编译模板代码,即 <template> 标签中包含的部分

使用:

const result = compileTemplate({
  source: '<div><img src="../images/profile.png" /></div>',
  filename: 'example.san',
  transformAssetUrls: true,
});

方法 / 属性:

方法 / 属性描述类型
source源码string
filename文件名string
id一般用在 scoped css 时string
scopedscoped css 开关boolean
transformAssetUrls将 url 转换为 requireboolean
compileANode编译为 anode / apack'aNode'/'aPack'/'none'
preprocessLang预处理语言,pugjs 等string
preprocessOptions预处理的选项,传递给预处理器object

返回:

{
    code: '<div><img src="require(../images/profile.png);"></div>',
    source: '<div><img src="../images/profile.png" /></div>'
}

compileStyle / compileStyleAsync

描述:编译样式代码,即 <style> 标签中包含的部分

使用:

const style = parseSFC({
  source: `<style lang="less">@red: rgb(255, 0, 0);\n.color { color: @red; }\n</style>`,
  filename: 'test.san',
}).styles[0] as any;

const result = compileStyle({
  id: 'test',
  filename: 'test.san',
  source: style.content,
  scoped: true,
  map: style.map,
  preprocessLang: style.lang,
});

方法 / 属性:

方法 / 属性描述类型
source源码string
filename文件名string
id添加 scoped css idstring
scopedscoped css 开关boolean
modulescss modules 开关boolean
mute去除 postcss 控制台信息,默认为 trueboolean
preprocessLang预处理语言,less sass 等string
preprocessOptions预处理的选项,传递给预处理器object
postcssOptionspostcss 的选项,直接传递给它object
postcssPluginspostcss 的插件,直接传递给它object
mapsourcemap 的 map,如 less => css 的映射object

返回:

{
  code: '.color[test] {\n  color: #ff0000;\n}\n' // 转换后的代码,
  source: '.color {\n  color: #ff0000;\n}\n' // 源码,
  rawResult: LazyResult // postcss 异步结果,
  map: outMap && outMap.toJSON() // 经过两步转换的 sourcemap,
  errors,
  cssHashMap: {} // css modules 编译结果
}

compileScript

描述:直接使用 ts 的 transpile 方法

export const compileScript = (source: string, config: CompilerOptions) => {
  return typescrtipt.transpile(source, config);
};

如果不清楚,可以参考 test 目录下的测试文件

LICENSE

Copyright (c) Baidu Inc. All rights reserved.

This source code is licensed under the MIT license.