vue-simple-compiler
Version:
A lib to compile Vue Single-File Component into plain JavaScript & CSS.
56 lines (55 loc) • 2.23 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.resolveImports = exports.tsTransform = void 0;
const typescript_1 = __importDefault(require("typescript"));
const compiler_sfc_1 = require("vue/compiler-sfc");
const constants_1 = require("./constants");
const options_1 = require("./options");
const defaultTsCompilerOptions = {
module: typescript_1.default.ModuleKind.ESNext,
target: typescript_1.default.ScriptTarget.ESNext,
jsx: typescript_1.default.JsxEmit.Preserve,
};
const tsTransform = (src, options, runtime) => {
const result = (runtime || typescript_1.default).transpileModule(src, { compilerOptions: options || defaultTsCompilerOptions });
return {
code: result.outputText,
};
};
exports.tsTransform = tsTransform;
/**
* Resolve all the import statements in the generated code.
* 1. `*.js` `*.jsx` `*.ts` `*.tsx` -> `*.js`
* 2. `*.vue` -> `*.vue.js`
* 3. prepend all the CSS imports
*
* @param code the generated code from vue/compiler-sfc
* @param cssImportList an array of css import strings to prepend
* @param options the compiler options
* @returns the resolved code, including content and source map
*/
const resolveImports = (code, options) => {
const s = new compiler_sfc_1.MagicString(code);
const resolver = options?.resolver ?? ((x) => x);
const ast = (0, compiler_sfc_1.babelParse)(code, {
sourceFilename: options?.filename ?? constants_1.FILENAME,
sourceType: 'module',
}).program.body;
ast.forEach((node) => {
if (node.type === 'ImportDeclaration') {
const srcPath = resolver(node.source.value);
if (srcPath) {
const destPath = (0, options_1.getDestPath)(srcPath);
if (typeof node.source.start === 'number' &&
typeof node.source.end === 'number') {
s.overwrite(node.source.start, node.source.end, JSON.stringify(destPath));
}
}
}
});
return s.toString();
};
exports.resolveImports = resolveImports;