Repository: egoist/vue-compile
Branch: master
Commit: 03853f96898b
Files: 33
Total size: 38.5 KB
Directory structure:
gitextract_b7opvyms/
├── .editorconfig
├── .eslintrc
├── .gitattributes
├── .gitignore
├── .prettierrc
├── LICENSE
├── README.md
├── babel.js
├── circle.yml
├── jest.config.js
├── package.json
├── src/
│ ├── babel/
│ │ └── preset.ts
│ ├── cli.ts
│ ├── compileScript.ts
│ ├── compileStyles.ts
│ ├── compileTemplate.ts
│ ├── importLocal.ts
│ ├── index.ts
│ ├── script-compilers/
│ │ └── babel.ts
│ ├── style-compilers/
│ │ ├── postcss.ts
│ │ ├── sass.ts
│ │ └── stylus.ts
│ ├── types.ts
│ ├── utils.ts
│ └── writeSFC.ts
├── test/
│ ├── fixture/
│ │ ├── custom-blocks/
│ │ │ └── foo.vue
│ │ ├── keep-async-function/
│ │ │ └── foo.vue
│ │ ├── keep-ts-block/
│ │ │ └── foo.vue
│ │ ├── script-block/
│ │ │ └── foo.vue
│ │ └── script-setup/
│ │ └── foo.vue
│ └── index.test.ts
├── tsconfig.build.json
└── tsconfig.json
================================================
FILE CONTENTS
================================================
================================================
FILE: .editorconfig
================================================
root = true
[*]
indent_style = space
indent_size = 2
end_of_line = lf
charset = utf-8
trim_trailing_whitespace = true
insert_final_newline = true
[*.md]
trim_trailing_whitespace = false
[*.test.ts]
trim_trailing_whitespace = false
================================================
FILE: .eslintrc
================================================
{
"extends": ["xo-typescript", "rem", "prettier"],
"plugins": ["prettier"],
"env": {
"jest": true
},
"rules": {
"unicorn/filename-case": "off",
"unicorn/no-abusive-eslint-disable": "off",
"@typescript-eslint/no-var-requires": "off",
"@typescript-eslint/restrict-template-expressions": "off"
}
}
================================================
FILE: .gitattributes
================================================
* text=auto
================================================
FILE: .gitignore
================================================
node_modules
test/fixture/output
*.log
dist/
================================================
FILE: .prettierrc
================================================
"@egoist/prettier-config"
================================================
FILE: LICENSE
================================================
The MIT License (MIT)
Copyright (c) egoist <0x142857@gmail.com> (https://github.com/egoist)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
================================================
FILE: README.md
================================================
# vue-compile
Compile the blocks in Vue single-file components to JS/CSS from Babel/Sass/Stylus.
## Why This Approach
You may want to publish `.vue` files instead of transformed `.js` files on npm because the `.vue` file is preferred in some scenarioes, e.g. `vue-server-renderer` can inline critical CSS from `<style>` blocks.
This tool will transform each block in the `.vue` file to their standard conterparts like `sass` -> `css` so your users don't have to install additional libraries to compile it.
It also provides a `--preserve-ts-block` flag if you don't want to transpile TypeScript, because tools like Vite supports TypeScript out of the box. In this way you don't need to generate `.d.ts` for your Vue components either, thanks to [Volar](https://github.com/johnsoncodehk/volar).
## Install
```bash
yarn global add vue-compile
# or
npm i -g vue-compile
```
## Usage
```bash
# normalize a .vue file
vue-compile example.vue -o output.vue
# normalize a directory
# non .vue files will be simply copied to output directory
vue-compile src -o lib
```
__Then you can publish normalized `.vue` files to npm registry without compiling them to `.js` files.__
Supported transforms (via `lang` attribute):
- `<template>` tag:
- `html` (default)
- `<script>` tag:
- `babel` (default): use our default [babel preset](./lib/babel/preset.js) or your own `.babelrc`
- `ts` `typescript`: use our default [babel preset](./lib/babel/preset.js) + `@babel/preset-typescript`, you can use `--preserve-ts-block` flag to preserve types, i.e. disable typescript transformation
- `<style>` tag:
- `postcss` (default): use your own `postcss.config.js`
- `stylus` `sass` `scss`
- Custom blocks: They are not touched.
Gotchas:
- We only handle `src` attribute for `<style>` blocks, we simply replace the extension with `.css` and remove the `lang` attribute.
<details><summary>Example</summary><br>
In:
```vue
<template>
<div class="foo">
{{ count }}
</div>
</template>
<script>
export default {
data() {
return {
count: 0
}
}
}
</script>
<style lang="scss" src="./foo.scss">
<style lang="stylus" scoped>
@import './colors.styl'
.foo
color: $color
</style>
```
Out:
```vue
<template>
<div class="foo">
{{ count }}
</div>
</template>
<script>
export default {
data: function data() {
return {
count: 0
};
}
};
</script>
<style src="./foo.css">
<style scoped>
.foo {
color: #f00;
}
</style>
```
</details>
### Compile Standalone CSS Files
CSS files like `.css` `.scss` `.sass` `.styl` will be compiled to output directory with `.css` extension, all relevant `import` statements in `.js` `.ts` or `<script>` blocks will be changed to use `.css` extension as well.
You can exclude them using the `--exclude "**/*.{css,scss,sass,styl}"` flag.
## Contributing
1. Fork it!
2. Create your feature branch: `git checkout -b my-new-feature`
3. Commit your changes: `git commit -am 'Add some feature'`
4. Push to the branch: `git push origin my-new-feature`
5. Submit a pull request :D
## Author
**vue-compile** © [egoist](https://github.com/egoist), Released under the [MIT](./LICENSE) License.<br>
Authored and maintained by egoist with help from contributors ([list](https://github.com/egoist/vue-compile/contributors)).
> [github.com/egoist](https://github.com/egoist) · GitHub [@egoist](https://github.com/egoist) · Twitter [@_egoistlily](https://twitter.com/_egoistlily)
================================================
FILE: babel.js
================================================
/* eslint-disable */
module.exports = require('./dist/babel/preset')
================================================
FILE: circle.yml
================================================
version: 2
jobs:
build:
docker:
- image: circleci/node:latest
branches:
ignore:
- gh-pages # list of branches to ignore
- /release\/.*/ # or ignore regexes
steps:
- checkout
- restore_cache:
key: dependency-cache-{{ checksum "yarn.lock" }}
- run:
name: install dependences
command: yarn
- save_cache:
key: dependency-cache-{{ checksum "yarn.lock" }}
paths:
- ./node_modules
- run:
name: test
command: yarn test
- run:
name: release
command: npx semantic-release
================================================
FILE: jest.config.js
================================================
module.exports = {
testEnvironment: 'node',
transform: {
'^.+\\.tsx?$': '@sucrase/jest-plugin',
},
testRegex: '(/__test__/.*|(\\.|/)(test|spec))\\.tsx?$',
testPathIgnorePatterns: ['/node_modules/', '/dist/', '/types/'],
moduleFileExtensions: ['ts', 'tsx', 'js', 'jsx', 'json', 'node'],
}
================================================
FILE: package.json
================================================
{
"name": "vue-compile",
"version": "0.0.0-semantic-release",
"description": "Pre-compile each blocks of your Vue single-file components.",
"repository": {
"url": "egoist/vue-compile",
"type": "git"
},
"main": "dist/index.js",
"bin": "dist/cli.js",
"types": "dist/index.d.ts",
"files": [
"dist/",
"babel.js"
],
"scripts": {
"test": "npm run lint && jest",
"lint": "eslint src/**/*.ts",
"build": "tsc -p tsconfig.build.json",
"prepublishOnly": "npm run build",
"postinstall": "node -e \"console.log('\\u001b[35m\\u001b[1mLove vue-compile? You can now donate to support the author:\\u001b[22m\\u001b[39m\\n> \\u001b[36mhttps://github.com/sponsors/egoist\\u001b[39m')\""
},
"author": "egoist <0x142857@gmail.com>",
"license": "MIT",
"dependencies": {
"@babel/core": "^7.13.15",
"@babel/plugin-syntax-typescript": "^7.12.13",
"@babel/preset-env": "^7.13.15",
"@babel/preset-typescript": "^7.13.0",
"@vue/compiler-sfc": "^3.0.11",
"cac": "^6.7.2",
"chalk": "^4.1.0",
"chokidar": "^3.5.1",
"debug": "^4.3.1",
"fast-glob": "^3.2.5",
"fs-extra": "^9.1.0",
"is-binary-path": "^2.1.0",
"joycon": "^3.0.1",
"lodash.clonedeep": "^4.5.0",
"postcss": "^8.2.10",
"postcss-load-config": "^3.0.1",
"resolve": "^1.20.0",
"resolve-from": "^5.0.0",
"stringify-attributes": "^2.0.0"
},
"devDependencies": {
"@egoist/prettier-config": "^0.1.0",
"@sucrase/jest-plugin": "^2.1.0",
"@types/debug": "^4.1.4",
"@types/fs-extra": "^8.0.0",
"@types/is-binary-path": "^2.1.0",
"@types/jest": "^26.0.14",
"@types/lodash.clonedeep": "^4.5.6",
"@types/node-sass": "^4.11.0",
"@types/stringify-attributes": "^2.0.0",
"@typescript-eslint/eslint-plugin": "^4.22.0",
"@typescript-eslint/parser": "^4.22.0",
"eslint": "^7.24.0",
"eslint-config-prettier": "^8.2.0",
"eslint-config-rem": "^4.0.0",
"eslint-config-xo-typescript": "^0.38.0",
"eslint-plugin-prettier": "^3.4.0",
"husky": "^4.3.0",
"jest": "^24.8.0",
"lint-staged": "^10.4.0",
"prettier": "^2.2.1",
"stylus": "^0.54.5",
"typescript": "^4.2.4",
"vue": "^3.0.11"
},
"husky": {
"hooks": {
"pre-commit": "lint-staged"
}
},
"lint-staged": {
"{src}/**/*.ts": [
"eslint --fix"
]
},
"release": {
"branch": "master"
}
}
================================================
FILE: src/babel/preset.ts
================================================
import { PluginObj, types as Types } from '@babel/core'
import { cssExtensionsRe } from '../utils'
export default (_: any, opts: { transformTypeScript: boolean }) => {
const presets = []
if (opts.transformTypeScript) {
presets.push(require.resolve('@babel/preset-typescript'))
}
presets.push([
require.resolve('@babel/preset-env'),
{
modules: false,
targets: {
edge: '79',
// Node 12 is no longer maintained, and let's pretend Node 13 didn't exist
node: '14',
},
},
])
const plugins = [replaceExtensionInImports]
if (!opts.transformTypeScript) {
plugins.push(require('@babel/plugin-syntax-typescript'))
}
return {
presets,
plugins,
}
}
function replaceExtensionInImports(opts: { types: typeof Types }): PluginObj {
const { types: t } = opts
return {
name: 'replace-extension-in-imports',
visitor: {
ImportDeclaration(path) {
if (cssExtensionsRe.test(path.node.source.value)) {
path.node.source.value = path.node.source.value.replace(
cssExtensionsRe,
'.css',
)
}
},
CallExpression(path) {
if ((path.node.callee as Types.Identifier).name === 'require') {
const arg: any = path.get('arguments.0')
if (arg) {
const res = arg.evaluate()
if (res.confident && cssExtensionsRe.test(res.value)) {
path.node.arguments = [
t.stringLiteral(res.value.replace(cssExtensionsRe, '.css')),
]
}
}
}
},
},
}
}
================================================
FILE: src/cli.ts
================================================
#!/usr/bin/env node
import path from 'path'
import chalk from 'chalk'
if (parseInt(process.versions.node, 10) < 8) {
console.error(
chalk.red('The "vue-compile" module requires Node.js 8 or above!'),
)
console.error(chalk.dim(`Current version: ${process.versions.node}`))
process.exit(1)
}
async function main(): Promise<void> {
const { cac } = await import('cac')
// eslint-disable-next-line @typescript-eslint/no-var-requires
const { version } = require('../package.json')
const cli = cac('vue-compile')
cli
.command('[input]', 'Normalize input file or directory', {
ignoreOptionDefaultValue: true,
})
.usage('[input] [options]')
.action(async (input: string, flags: any) => {
const options = {
input,
...flags,
}
if (!options.input) {
delete options.input
}
if (options.debug === true) {
process.env.DEBUG = 'vue-compile:*'
} else if (typeof options.debug === 'string') {
process.env.DEBUG = `vue-compile:${options.debug}`
}
const { createCompiler } = await import('.')
if (!options.input) {
cli.outputHelp()
return
}
const compiler = createCompiler(options)
compiler.on('normalized', async (input: string, output: string) => {
if (!compiler.options.debug) {
const { humanlizePath } = await import('./utils')
console.log(
`${chalk.magenta(humanlizePath(input))} ${chalk.dim(
'->',
)} ${chalk.green(humanlizePath(output))}`,
)
}
})
await compiler.normalize().catch(handleError)
if (flags.watch) {
const { watch } = await import('chokidar')
watch('.', {
cwd: compiler.isInputFile
? path.resolve(path.dirname(input))
: path.resolve(input),
ignoreInitial: true,
ignorePermissionErrors: true,
ignored: '**/{node_modules,dist,.git,public}/**',
}).on('all', (_, file) => {
console.log(chalk.bold(`Rebuilding because ${file} changed..`))
compiler.normalize().catch(handleError)
})
}
})
.option('-o, --output <file|directory>', 'Output path')
.option(
'-i, --include <glob>',
'A glob pattern to include from input directory',
)
.option(
'-e, --exclude <glob>',
'A glob pattern to exclude from input directory',
)
.option('--no-babelrc', 'Disable .babelrc file')
.option('--preserve-ts-block', `Preserve TypeScript types in script block`)
.option('-w, --watch', 'Enable watch mode')
cli.option('--debug', 'Show debug logs')
cli.version(version)
cli.help()
cli.parse()
}
function handleError(error: Error): void {
console.error(error.stack)
process.exit(1)
}
main().catch(handleError)
================================================
FILE: src/compileScript.ts
================================================
import { SFCScriptBlock } from '@vue/compiler-sfc'
import { notSupportedLang } from './utils'
import { ScriptCompilerContext } from './types'
export const compileScript = async (
script: SFCScriptBlock | null,
ctx: ScriptCompilerContext,
): Promise<SFCScriptBlock | null> => {
if (!script) return script
const code = script.content.replace(/^\/\/$/gm, '')
if (
!script.lang ||
script.lang === 'esnext' ||
script.lang === 'babel' ||
script.lang === 'ts' ||
script.lang === 'typescript'
) {
script.content = await import(
'./script-compilers/babel'
).then(async ({ compile }) => compile(code, ctx))
} else {
throw new Error(notSupportedLang(script.lang, 'script'))
}
return script
}
================================================
FILE: src/compileStyles.ts
================================================
import { SFCStyleBlock } from '@vue/compiler-sfc'
import { notSupportedLang } from './utils'
export const compileStyles = async (
styles: SFCStyleBlock[],
{ filename }: { filename: string },
): Promise<SFCStyleBlock[]> => {
return Promise.all(
styles.map(async (style) => {
// Do not handle "src" import
// Until we figure out how to handle it
if (style.src) return style
const { content } = style
if (style.lang === 'stylus') {
style.content = await require('./style-compilers/stylus').compile(
content,
{
filename,
},
)
} else if (!style.lang || style.lang === 'postcss') {
style.content = await require('./style-compilers/postcss').compile(
content,
{
filename,
},
)
} else if (style.lang === 'scss' || style.lang === 'sass') {
style.content = await require('./style-compilers/sass').compile(
content,
{
filename,
indentedSyntax: style.lang === 'sass',
},
)
} else if (style.lang) {
throw new Error(notSupportedLang(style.lang, 'style'))
}
return style
}),
)
}
================================================
FILE: src/compileTemplate.ts
================================================
import { SFCTemplateBlock } from '@vue/compiler-sfc'
export const compileTemplate = <T = SFCTemplateBlock | null>(template: T): T =>
template
================================================
FILE: src/importLocal.ts
================================================
import resolveFrom from 'resolve-from'
export const importLocal = (dir: string, name: string, fallback?: string): any => {
const found =
resolveFrom.silent(dir, name) ||
(fallback && resolveFrom.silent(dir, fallback))
if (!found) {
throw new Error(
`You need to install "${name}"${
fallback ? ` or "${fallback}"` : ''
} in current directory!`
)
}
return require(found)
}
================================================
FILE: src/index.ts
================================================
import path from 'path'
import { EventEmitter } from 'events'
import fs from 'fs-extra'
import JoyCon from 'joycon'
import isBinaryPath from 'is-binary-path'
import createDebug from 'debug'
import { parse } from '@vue/compiler-sfc'
import glob from 'fast-glob'
import cloneDeep from 'lodash.clonedeep'
import {
replaceContants,
cssExtensionsRe,
jsExtensionsRe,
isDefined,
} from './utils'
import { compileScript } from './compileScript'
import { compileStyles } from './compileStyles'
import { compileTemplate } from './compileTemplate'
import { writeSFC } from './writeSFC'
const debug = createDebug('vue-compile:cli')
type OptionContants = Record<string, string | boolean | number>
interface InputOptions {
config?: boolean | string
input: string
output: string
constants?: OptionContants
babelrc?: boolean
include?: string[]
exclude?: string[]
debug?: boolean
preserveTsBlock?: boolean
}
interface NormalizedOptions {
input: string
output: string
constants?: OptionContants
babelrc?: boolean
include?: string[]
exclude?: string[]
debug?: boolean
preserveTsBlock?: boolean
}
class VueCompile extends EventEmitter {
options: NormalizedOptions
isInputFile?: boolean
constructor(options: InputOptions) {
super()
if (options.config !== false) {
const joycon = new JoyCon({
files: [
typeof options.config === 'string'
? options.config
: 'vue-compile.config.js',
],
stopDir: path.dirname(process.cwd()),
})
const { data: config, path: configPath } = joycon.loadSync()
if (configPath) {
debug(`Using config file: ${configPath}`)
}
options = { ...options, ...config }
}
this.options = this.normalizeOptions(options)
this.isInputFile = fs.statSync(this.options.input).isFile()
}
normalizeOptions(options: InputOptions): NormalizedOptions {
return {
...options,
input: path.resolve(options.input),
output: path.resolve(options.output),
}
}
async normalize(): Promise<void> {
if (!this.options.input) {
return
}
if (this.isInputFile) {
if (!this.options.output) {
throw new Error('You must specify the path to output file.')
}
await this.normalizeFile(this.options.input, this.options.output)
} else {
if (!this.options.output) {
throw new Error('You must specify the path to output directory.')
}
await this.normalizeDir(this.options.input, this.options.output)
}
}
async normalizeFile(input: string, outFile: string): Promise<void> {
if (isBinaryPath(input)) {
const buffer = await fs.readFile(input)
return this.writeBinary(buffer, {
filename: input,
outFile,
})
}
let source = await fs.readFile(input, 'utf8')
source = replaceContants(source, this.options.constants)
const ctx = {
filename: input,
outFile,
babelrc: this.options.babelrc,
transformTypeScript: true,
}
if (!input.endsWith('.vue')) {
return this.writeText(source, ctx)
}
ctx.transformTypeScript = !this.options.preserveTsBlock
const sfc = cloneDeep(
parse(source, {
filename: input,
}),
)
const script = await compileScript(sfc.descriptor.script, ctx)
const scriptSetup = await compileScript(sfc.descriptor.scriptSetup, ctx)
const template = compileTemplate(sfc.descriptor.template)
const styles = await compileStyles(sfc.descriptor.styles, ctx)
await writeSFC(
{
scripts: [script, scriptSetup].filter(isDefined).sort((a, b) => {
return a.loc.start > b.loc.start ? -1 : 1
}),
styles,
template,
customBlocks: sfc.descriptor.customBlocks,
preserveTsBlock: this.options.preserveTsBlock,
},
outFile,
)
this.emit('normalized', input, outFile)
}
async normalizeDir(input: string, outDir: string): Promise<void> {
const include = [...(this.options.include ?? [])]
const exclude = [...(this.options.exclude ?? [])]
const files = await glob(include.length > 0 ? include : ['**/*'], {
cwd: input,
ignore: ['**/node_modules/**'].concat(exclude),
})
await Promise.all(
files.map(async (file: string) => {
return this.normalizeFile(
path.join(input, file),
path.join(outDir, file),
)
}),
)
}
async writeText(
source: string,
{
filename,
outFile,
babelrc,
transformTypeScript,
}: {
filename: string
outFile: string
babelrc?: boolean
transformTypeScript: boolean
},
): Promise<void> {
let output
if (jsExtensionsRe.test(filename)) {
output = await import('./script-compilers/babel').then(
async ({ compile }) => {
return compile(source, {
filename,
babelrc,
transformTypeScript,
})
},
)
} else if (filename.endsWith('.css')) {
output = await import('./style-compilers/postcss').then(
async ({ compile }) => {
return compile(source, { filename })
},
)
} else if (/\.s[ac]ss$/.test(filename)) {
const basename = path.basename(filename)
if (basename.startsWith('_')) {
// Ignore sass partial files
return
}
output = await import('./style-compilers/sass').then(
async ({ compile }) => {
return compile(source, {
filename,
indentedSyntax: filename.endsWith('.sass'),
})
},
)
} else if (/\.styl(us)?/.test(filename)) {
output = await import('./style-compilers/stylus').then(
async ({ compile }) => {
return compile(source, {
filename,
})
},
)
} else {
output = source
}
outFile = outFile.replace(cssExtensionsRe, '.css')
outFile = outFile.replace(jsExtensionsRe, '.js')
await fs.outputFile(outFile, output, 'utf8')
this.emit('normalized', filename, outFile)
}
async writeBinary(
source: Buffer,
{ filename, outFile }: { filename: string; outFile: string },
): Promise<void> {
await fs.outputFile(outFile, source, 'utf8')
this.emit('normalized', filename, outFile)
}
}
export const createCompiler = (opts: InputOptions): VueCompile =>
new VueCompile(opts)
================================================
FILE: src/script-compilers/babel.ts
================================================
import path from 'path'
import createDebug from 'debug'
import { TransformOptions } from '@babel/core'
import preset from '../babel/preset'
import { ScriptCompilerContext } from '../types'
import { getBabelConfigFile } from '../utils'
const debug = createDebug('vue-compile:script')
export const compile = async (
code: string,
{ filename, babelrc, transformTypeScript }: ScriptCompilerContext,
): Promise<string> => {
const cwd = path.dirname(filename)
const babelConfigFile = getBabelConfigFile(cwd, babelrc)
const config: TransformOptions = {
filename: filename.endsWith('.vue') ? `${filename}.vue.ts` : filename,
presets: [[preset, { transformTypeScript }]],
}
if (babelConfigFile) {
config.babelrc = true
debug(`Using Babel config file at ${babelConfigFile}`)
} else {
config.babelrc = false
}
return require('@babel/core').transform(code, config).code
}
================================================
FILE: src/style-compilers/postcss.ts
================================================
import path from 'path'
import createDebug from 'debug'
const debug = createDebug('vue-compile:style')
const cache = new Map()
export const compile = async (
code: string,
{ filename }: { filename: string }
): Promise<string> => {
const ctx = {
file: {
extname: path.extname(filename),
dirname: path.dirname(filename),
basename: path.basename(filename)
},
options: {}
}
const cwd = path.dirname(filename)
const config =
cache.get(cwd) ||
(await require('postcss-load-config')(ctx, cwd, {
argv: false
}).catch((error: Error) => {
if (error.message.includes('No PostCSS Config found in')) {
return {}
}
throw error
}))
cache.set(cwd, config)
if (config.file) {
debug(`Using PostCSS config file at ${config.file}`)
}
const options = {
from: filename,
map: false,
...config.options
}
return import('postcss').then(async postcss => {
return postcss
.default(config.plugins || [])
.process(code, options)
.then(res => res.css)
})
}
================================================
FILE: src/style-compilers/sass.ts
================================================
import path from 'path'
import { promisify } from 'util'
import { SassRenderCallback, Options as SassRenderOptions } from 'node-sass'
import { importLocal } from '../importLocal'
const moduleRe = /^~([a-z0-9]|@).+/i
const getUrlOfPartial = (url: string): string => {
const parsedUrl = path.parse(url)
return `${parsedUrl.dir}${path.sep}_${parsedUrl.base}`
}
type SassRender = (
options: SassRenderOptions,
callback: SassRenderCallback,
) => void
export const compile = async (
code: string,
{ filename, indentedSyntax }: { filename: string; indentedSyntax?: boolean },
): Promise<string> => {
const sass: { render: SassRender } = importLocal(
path.dirname(filename),
'sass',
'node-sass',
)
const res = await promisify(sass.render.bind(sass))({
file: filename,
data: code,
indentedSyntax,
sourceMap: false,
importer: [
(url, importer, done) => {
if (!moduleRe.test(url)) {
done({ file: url })
return
}
const moduleUrl = url.slice(1)
const partialUrl = getUrlOfPartial(moduleUrl)
const options = {
basedir: path.dirname(importer),
extensions: ['.scss', '.sass', '.css'],
}
const finishImport = (id: string): void => {
done({
// Do not add `.css` extension in order to inline the file
file: id.endsWith('.css') ? id.replace(/\.css$/, '') : id,
})
}
const next = (): void => {
// Catch all resolving errors, return the original file and pass responsibility back to other custom importers
done({ file: url })
}
const resolvePromise = promisify(require('resolve'))
// Give precedence to importing a partial
resolvePromise(partialUrl, options)
.then(finishImport)
.catch((error: any) => {
if (error.code === 'MODULE_NOT_FOUND' || error.code === 'ENOENT') {
resolvePromise(moduleUrl, options).then(finishImport).catch(next)
} else {
next()
}
})
},
],
})
return res.css.toString()
}
================================================
FILE: src/style-compilers/stylus.ts
================================================
import path from 'path'
import { promisify } from 'util'
import { importLocal } from '../importLocal'
export const compile = async (code: string, { filename }: { filename: string }): Promise<string> => {
const stylus = importLocal(path.dirname(filename), 'stylus')
return promisify(stylus.render.bind(stylus))(code, { filename })
}
================================================
FILE: src/types.ts
================================================
export interface ScriptCompilerContext {
filename: string
babelrc?: boolean
transformTypeScript: boolean
}
================================================
FILE: src/utils.ts
================================================
import path from 'path'
import { loadPartialConfig } from '@babel/core'
export const humanlizePath = (p: string): string =>
path.relative(process.cwd(), p)
export const notSupportedLang = (lang: string, tag: string): string => {
return `"${lang}" is not supported for <${tag}> tag currently, wanna contribute this feature?`
}
function escapeRe(str: string): string {
return str.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&')
}
export const replaceContants = (
content: string,
constants?: Record<string, any>,
): string => {
if (!constants) return content
const RE = new RegExp(
`\\b(${Object.keys(constants).map(escapeRe).join('|')})\\b`,
'g',
)
content = content.replace(RE, (_, p1) => {
return constants[p1]
})
return content
}
export const cssExtensionsRe = /\.(css|s[ac]ss|styl(us)?)$/
export const jsExtensionsRe = /\.[jt]sx?$/
const babelConfigCache: Map<string, string | undefined> = new Map()
/**
* Find babel config file in cwd
* @param cwd
* @param babelrc Whether to load babel config file
*/
export const getBabelConfigFile = (cwd: string, babelrc?: boolean) => {
const file: string | undefined =
babelrc === false
? undefined
: babelConfigCache.get(cwd) ?? loadPartialConfig()?.babelrc
babelConfigCache.set(cwd, file)
return file
}
export function isDefined<T>(value: T | undefined | null): value is T {
return value != null
}
================================================
FILE: src/writeSFC.ts
================================================
import path from 'path'
import fs from 'fs-extra'
import stringifyAttrs from 'stringify-attributes'
import {
SFCScriptBlock,
SFCStyleBlock,
SFCTemplateBlock,
SFCBlock,
} from '@vue/compiler-sfc'
import { cssExtensionsRe } from './utils'
export const writeSFC = async (
{
scripts,
styles,
template,
customBlocks,
preserveTsBlock,
}: {
scripts: SFCScriptBlock[]
styles: SFCStyleBlock[]
template: SFCTemplateBlock | null
customBlocks: SFCBlock[]
preserveTsBlock?: boolean
},
outFile: string,
): Promise<void> => {
const parts = []
if (template) {
parts.push(
`<template${stringifyAttrs(template.attrs)}>${template.content
.replace(/\n$/, '')
.replace(/^/gm, ' ')}\n</template>`,
)
}
scripts.forEach((script) => {
parts.push(
`<script${preserveTsBlock && script.lang === 'ts' ? ' lang="ts"' : ''}${
script.setup ? ' setup' : ''
}>\n${script.content.trim()}\n</script>`,
)
})
if (styles.length > 0) {
for (const style of styles) {
const attrs = { ...style.attrs }
delete attrs.lang
if (style.src) {
attrs.src = style.src.replace(cssExtensionsRe, '.css')
parts.push(`<style${stringifyAttrs(attrs)}></style>`)
} else {
parts.push(
`<style${stringifyAttrs(attrs)}>\n${style.content.trim()}\n</style>`,
)
}
}
}
if (customBlocks) {
for (const block of customBlocks) {
parts.push(
`<${block.type}${stringifyAttrs(block.attrs)}>${
block.content ? block.content.trim() : ''
}</${block.type}>`,
)
}
}
await fs.ensureDir(path.dirname(outFile))
await fs.writeFile(outFile, parts.join('\n\n'), 'utf8')
}
================================================
FILE: test/fixture/custom-blocks/foo.vue
================================================
<template>
<div></div>
</template>
<script>
export default {
}
</script>
<foo>
this is a custom block
</foo>
================================================
FILE: test/fixture/keep-async-function/foo.vue
================================================
<script lang="ts">
export default {
async setup() {
console.log('a')
},
}
</script>
================================================
FILE: test/fixture/keep-ts-block/foo.vue
================================================
<script lang="ts">
export default {
setup() {
let a: string = '1'
return {
a,
}
},
}
</script>
================================================
FILE: test/fixture/script-block/foo.vue
================================================
<script lang="ts">
import { ref } from 'vue'
export default {
setup() {
const a = ref('a')
return {
a: a.value ?? 'a',
}
},
}
</script>
================================================
FILE: test/fixture/script-setup/foo.vue
================================================
<script lang="ts">
export const foo = 'foo'
</script>
<script lang="ts" setup>
import { defineProps, PropType } from 'vue'
const props = defineProps({
foo: Number as PropType<number>,
})
</script>
<template>
<div>{{ props.foo }}</div>
</template>
================================================
FILE: test/index.test.ts
================================================
import path from 'path'
import fs from 'fs-extra'
import { createCompiler } from '../src'
const fixture = (...args: string[]): string =>
path.resolve(__dirname, 'fixture', ...args)
const tmp = (name: string): string => fixture('output', name)
test('script block', async () => {
const outDir = tmp('script-block')
const compiler = createCompiler({
input: fixture('script-block'),
output: outDir,
})
await compiler.normalize()
const content = await fs.readFile(path.join(outDir, 'foo.vue'), 'utf8')
expect(content).toMatchInlineSnapshot(`
"<script>
import { ref } from 'vue';
export default {
setup() {
var _a$value;
const a = ref('a');
return {
a: (_a$value = a.value) !== null && _a$value !== void 0 ? _a$value : 'a'
};
}
};
</script>"
`)
})
test('script setup', async () => {
const outDir = tmp('script-setup')
const compiler = createCompiler({
input: fixture('script-setup'),
output: outDir,
})
await compiler.normalize()
const content = await fs.readFile(path.join(outDir, 'foo.vue'), 'utf8')
expect(content).toMatchInlineSnapshot(`
"<template>
<div>{{ props.foo }}</div>
</template>
<script>
export const foo = 'foo';
</script>
<script setup>
import { defineProps } from 'vue';
const props = defineProps({
foo: Number
});
</script>"
`)
})
test('custom blocks', async () => {
const outDir = tmp('custom-blocks')
const compiler = createCompiler({
input: fixture('custom-blocks'),
output: outDir,
})
await compiler.normalize()
const content = await fs.readFile(path.join(outDir, 'foo.vue'), 'utf8')
expect(content).toMatchInlineSnapshot(`
"<template>
<div></div>
</template>
<script>
export default {};
</script>
<foo>this is a custom block</foo>"
`)
})
test('keep ts block', async () => {
const outDir = tmp('keep-ts-block')
const compiler = createCompiler({
input: fixture('keep-ts-block'),
output: outDir,
preserveTsBlock: true,
})
await compiler.normalize()
const content = await fs.readFile(path.join(outDir, 'foo.vue'), 'utf8')
expect(content).toMatchInlineSnapshot(`
"<script lang=\\"ts\\">
export default {
setup() {
let a: string = '1';
return {
a
};
}
};
</script>"
`)
})
test('keep-async-function', async () => {
const outDir = tmp('keep-async-function')
const compiler = createCompiler({
input: fixture('keep-async-function'),
output: outDir,
preserveTsBlock: true,
})
await compiler.normalize()
const content = await fs.readFile(path.join(outDir, 'foo.vue'), 'utf8')
expect(content).toMatchInlineSnapshot(`
"<script lang=\\"ts\\">
export default {
async setup() {
console.log('a');
}
};
</script>"
`)
})
================================================
FILE: tsconfig.build.json
================================================
{
"extends": "./tsconfig.json",
"compilerOptions": {
"outDir": "./dist",
"declaration": true,
"skipLibCheck": true
},
"include": ["src"]
}
================================================
FILE: tsconfig.json
================================================
{
"compilerOptions": {
/* Basic Options */
// "incremental": true, /* Enable incremental compilation */
"target": "es2019" /* Specify ECMAScript target version: 'ES3' (default), 'ES5', 'ES2015', 'ES2016', 'ES2017', 'ES2018', 'ES2019' or 'ESNEXT'. */,
"module": "commonjs" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', or 'ESNext'. */,
// "lib": [], /* Specify library files to be included in the compilation. */
// "allowJs": true, /* Allow javascript files to be compiled. */
// "checkJs": true, /* Report errors in .js files. */
// "jsx": "preserve", /* Specify JSX code generation: 'preserve', 'react-native', or 'react'. */
// "declaration": true, /* Generates corresponding '.d.ts' file. */
// "declarationMap": true, /* Generates a sourcemap for each corresponding '.d.ts' file. */
// "sourceMap": true, /* Generates corresponding '.map' file. */
// "outFile": "./", /* Concatenate and emit output to single file. */
// "rootDir": "./", /* Specify the root directory of input files. Use to control the output directory structure with --outDir. */
// "composite": true, /* Enable project compilation */
// "tsBuildInfoFile": "./", /* Specify file to store incremental compilation information */
// "removeComments": true, /* Do not emit comments to output. */
// "noEmit": true, /* Do not emit outputs. */
// "importHelpers": true, /* Import emit helpers from 'tslib'. */
// "downlevelIteration": true, /* Provide full support for iterables in 'for-of', spread, and destructuring when targeting 'ES5' or 'ES3'. */
// "isolatedModules": true, /* Transpile each file as a separate module (similar to 'ts.transpileModule'). */
/* Strict Type-Checking Options */
"strict": true /* Enable all strict type-checking options. */,
"noImplicitAny": true /* Raise error on expressions and declarations with an implied 'any' type. */,
"strictNullChecks": true /* Enable strict null checks. */,
"strictFunctionTypes": true /* Enable strict checking of function types. */,
"strictBindCallApply": true /* Enable strict 'bind', 'call', and 'apply' methods on functions. */,
"strictPropertyInitialization": true /* Enable strict checking of property initialization in classes. */,
"noImplicitThis": true /* Raise error on 'this' expressions with an implied 'any' type. */,
"alwaysStrict": true /* Parse in strict mode and emit "use strict" for each source file. */,
/* Additional Checks */
"noUnusedLocals": true /* Report errors on unused locals. */,
"noUnusedParameters": true /* Report errors on unused parameters. */,
"noImplicitReturns": true /* Report error when not all code paths in function return a value. */,
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
/* Module Resolution Options */
"moduleResolution": "node" /* Specify module resolution strategy: 'node' (Node.js) or 'classic' (TypeScript pre-1.6). */,
// "baseUrl": "./", /* Base directory to resolve non-absolute module names. */
// "paths": {}, /* A series of entries which re-map imports to lookup locations relative to the 'baseUrl'. */
// "rootDirs": [], /* List of root folders whose combined content represents the structure of the project at runtime. */
// "typeRoots": [], /* List of folders to include type definitions from. */
// "types": [], /* Type declaration files to be included in compilation. */
// "allowSyntheticDefaultImports": true, /* Allow default imports from modules with no default export. This does not affect code emit, just typechecking. */
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */
// "preserveSymlinks": true, /* Do not resolve the real path of symlinks. */
// "allowUmdGlobalAccess": true, /* Allow accessing UMD globals from modules. */
/* Source Map Options */
// "sourceRoot": "", /* Specify the location where debugger should locate TypeScript files instead of source locations. */
// "mapRoot": "", /* Specify the location where debugger should locate map files instead of generated locations. */
// "inlineSourceMap": true, /* Emit a single file with source maps instead of having a separate file. */
// "inlineSources": true, /* Emit the source alongside the sourcemaps within a single file; requires '--inlineSourceMap' or '--sourceMap' to be set. */
/* Experimental Options */
// "experimentalDecorators": true, /* Enables experimental support for ES7 decorators. */
// "emitDecoratorMetadata": true, /* Enables experimental support for emitting type metadata for decorators. */
}
}
gitextract_b7opvyms/ ├── .editorconfig ├── .eslintrc ├── .gitattributes ├── .gitignore ├── .prettierrc ├── LICENSE ├── README.md ├── babel.js ├── circle.yml ├── jest.config.js ├── package.json ├── src/ │ ├── babel/ │ │ └── preset.ts │ ├── cli.ts │ ├── compileScript.ts │ ├── compileStyles.ts │ ├── compileTemplate.ts │ ├── importLocal.ts │ ├── index.ts │ ├── script-compilers/ │ │ └── babel.ts │ ├── style-compilers/ │ │ ├── postcss.ts │ │ ├── sass.ts │ │ └── stylus.ts │ ├── types.ts │ ├── utils.ts │ └── writeSFC.ts ├── test/ │ ├── fixture/ │ │ ├── custom-blocks/ │ │ │ └── foo.vue │ │ ├── keep-async-function/ │ │ │ └── foo.vue │ │ ├── keep-ts-block/ │ │ │ └── foo.vue │ │ ├── script-block/ │ │ │ └── foo.vue │ │ └── script-setup/ │ │ └── foo.vue │ └── index.test.ts ├── tsconfig.build.json └── tsconfig.json
SYMBOL INDEX (18 symbols across 6 files)
FILE: src/babel/preset.ts
function replaceExtensionInImports (line 32) | function replaceExtensionInImports(opts: { types: typeof Types }): Plugi...
FILE: src/cli.ts
function main (line 13) | async function main(): Promise<void> {
function handleError (line 100) | function handleError(error: Error): void {
FILE: src/index.ts
type OptionContants (line 23) | type OptionContants = Record<string, string | boolean | number>
type InputOptions (line 25) | interface InputOptions {
type NormalizedOptions (line 37) | interface NormalizedOptions {
class VueCompile (line 48) | class VueCompile extends EventEmitter {
method constructor (line 53) | constructor(options: InputOptions) {
method normalizeOptions (line 78) | normalizeOptions(options: InputOptions): NormalizedOptions {
method normalize (line 86) | async normalize(): Promise<void> {
method normalizeFile (line 106) | async normalizeFile(input: string, outFile: string): Promise<void> {
method normalizeDir (line 158) | async normalizeDir(input: string, outDir: string): Promise<void> {
method writeText (line 176) | async writeText(
method writeBinary (line 243) | async writeBinary(
FILE: src/style-compilers/sass.ts
type SassRender (line 13) | type SassRender = (
FILE: src/types.ts
type ScriptCompilerContext (line 1) | interface ScriptCompilerContext {
FILE: src/utils.ts
function escapeRe (line 11) | function escapeRe(str: string): string {
function isDefined (line 54) | function isDefined<T>(value: T | undefined | null): value is T {
Condensed preview — 33 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (43K chars).
[
{
"path": ".editorconfig",
"chars": 234,
"preview": "root = true\n\n[*]\nindent_style = space\nindent_size = 2\nend_of_line = lf\ncharset = utf-8\ntrim_trailing_whitespace = true\ni"
},
{
"path": ".eslintrc",
"chars": 327,
"preview": "{\n \"extends\": [\"xo-typescript\", \"rem\", \"prettier\"],\n \"plugins\": [\"prettier\"],\n \"env\": {\n \"jest\": true\n },\n \"rule"
},
{
"path": ".gitattributes",
"chars": 12,
"preview": "* text=auto\n"
},
{
"path": ".gitignore",
"chars": 45,
"preview": "node_modules\ntest/fixture/output\n*.log\ndist/\n"
},
{
"path": ".prettierrc",
"chars": 26,
"preview": "\"@egoist/prettier-config\"\n"
},
{
"path": "LICENSE",
"chars": 1117,
"preview": "The MIT License (MIT)\n\nCopyright (c) egoist <0x142857@gmail.com> (https://github.com/egoist)\n\nPermission is hereby grant"
},
{
"path": "README.md",
"chars": 3458,
"preview": "\n# vue-compile\n\nCompile the blocks in Vue single-file components to JS/CSS from Babel/Sass/Stylus.\n\n## Why This Approach"
},
{
"path": "babel.js",
"chars": 69,
"preview": "/* eslint-disable */\nmodule.exports = require('./dist/babel/preset')\n"
},
{
"path": "circle.yml",
"chars": 642,
"preview": "version: 2\njobs:\n build:\n docker:\n - image: circleci/node:latest\n branches:\n ignore:\n - gh-pages"
},
{
"path": "jest.config.js",
"chars": 304,
"preview": "module.exports = {\n testEnvironment: 'node',\n transform: {\n '^.+\\\\.tsx?$': '@sucrase/jest-plugin',\n },\n testRegex"
},
{
"path": "package.json",
"chars": 2418,
"preview": "{\n \"name\": \"vue-compile\",\n \"version\": \"0.0.0-semantic-release\",\n \"description\": \"Pre-compile each blocks of your Vue "
},
{
"path": "src/babel/preset.ts",
"chars": 1614,
"preview": "import { PluginObj, types as Types } from '@babel/core'\nimport { cssExtensionsRe } from '../utils'\n\nexport default (_: a"
},
{
"path": "src/cli.ts",
"chars": 2863,
"preview": "#!/usr/bin/env node\nimport path from 'path'\nimport chalk from 'chalk'\n\nif (parseInt(process.versions.node, 10) < 8) {\n "
},
{
"path": "src/compileScript.ts",
"chars": 741,
"preview": "import { SFCScriptBlock } from '@vue/compiler-sfc'\nimport { notSupportedLang } from './utils'\nimport { ScriptCompilerCon"
},
{
"path": "src/compileStyles.ts",
"chars": 1238,
"preview": "import { SFCStyleBlock } from '@vue/compiler-sfc'\nimport { notSupportedLang } from './utils'\n\nexport const compileStyles"
},
{
"path": "src/compileTemplate.ts",
"chars": 145,
"preview": "import { SFCTemplateBlock } from '@vue/compiler-sfc'\n\nexport const compileTemplate = <T = SFCTemplateBlock | null>(templ"
},
{
"path": "src/importLocal.ts",
"chars": 418,
"preview": "import resolveFrom from 'resolve-from'\n\nexport const importLocal = (dir: string, name: string, fallback?: string): any ="
},
{
"path": "src/index.ts",
"chars": 6469,
"preview": "import path from 'path'\nimport { EventEmitter } from 'events'\nimport fs from 'fs-extra'\nimport JoyCon from 'joycon'\nimpo"
},
{
"path": "src/script-compilers/babel.ts",
"chars": 906,
"preview": "import path from 'path'\nimport createDebug from 'debug'\nimport { TransformOptions } from '@babel/core'\nimport preset fro"
},
{
"path": "src/style-compilers/postcss.ts",
"chars": 1076,
"preview": "import path from 'path'\nimport createDebug from 'debug'\n\nconst debug = createDebug('vue-compile:style')\n\nconst cache = n"
},
{
"path": "src/style-compilers/sass.ts",
"chars": 2156,
"preview": "import path from 'path'\nimport { promisify } from 'util'\nimport { SassRenderCallback, Options as SassRenderOptions } fro"
},
{
"path": "src/style-compilers/stylus.ts",
"chars": 337,
"preview": "import path from 'path'\nimport { promisify } from 'util'\nimport { importLocal } from '../importLocal'\n\nexport const comp"
},
{
"path": "src/types.ts",
"chars": 113,
"preview": "export interface ScriptCompilerContext {\n filename: string\n babelrc?: boolean\n transformTypeScript: boolean\n}\n"
},
{
"path": "src/utils.ts",
"chars": 1410,
"preview": "import path from 'path'\nimport { loadPartialConfig } from '@babel/core'\n\nexport const humanlizePath = (p: string): strin"
},
{
"path": "src/writeSFC.ts",
"chars": 1757,
"preview": "import path from 'path'\nimport fs from 'fs-extra'\nimport stringifyAttrs from 'stringify-attributes'\nimport {\n SFCScript"
},
{
"path": "test/fixture/custom-blocks/foo.vue",
"chars": 114,
"preview": "<template>\n <div></div>\n</template>\n\n<script>\nexport default {\n\n}\n</script>\n\n<foo>\nthis is a custom block\n</foo>\n"
},
{
"path": "test/fixture/keep-async-function/foo.vue",
"chars": 92,
"preview": "<script lang=\"ts\">\nexport default {\n async setup() {\n console.log('a')\n },\n}\n</script>\n"
},
{
"path": "test/fixture/keep-ts-block/foo.vue",
"chars": 117,
"preview": "<script lang=\"ts\">\nexport default {\n setup() {\n let a: string = '1'\n return {\n a,\n }\n },\n}\n</script>\n"
},
{
"path": "test/fixture/script-block/foo.vue",
"chars": 158,
"preview": "<script lang=\"ts\">\nimport { ref } from 'vue'\nexport default {\n setup() {\n const a = ref('a')\n return {\n a: a"
},
{
"path": "test/fixture/script-setup/foo.vue",
"chars": 254,
"preview": "<script lang=\"ts\">\nexport const foo = 'foo'\n</script>\n\n<script lang=\"ts\" setup>\nimport { defineProps, PropType } from 'v"
},
{
"path": "test/index.test.ts",
"chars": 3214,
"preview": "import path from 'path'\nimport fs from 'fs-extra'\nimport { createCompiler } from '../src'\n\nconst fixture = (...args: str"
},
{
"path": "tsconfig.build.json",
"chars": 159,
"preview": "{\n \"extends\": \"./tsconfig.json\",\n \"compilerOptions\": {\n \"outDir\": \"./dist\",\n \"declaration\": true,\n \"skipLibCh"
},
{
"path": "tsconfig.json",
"chars": 5397,
"preview": "{\n \"compilerOptions\": {\n /* Basic Options */\n // \"incremental\": true, /* Enable incremental com"
}
]
About this extraction
This page contains the full source code of the egoist/vue-compile GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 33 files (38.5 KB), approximately 10.6k tokens, and a symbol index with 18 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.