Skip to content

refactor: use compiler utils #129

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
Nov 25, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 3 additions & 3 deletions lib/add-template-mapping.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,12 @@ module.exports = function addTemplateMapping(
map,
beforeLines
) {
var afterLines = output.split(splitRE).length
var templateLine = content.slice(0, parts.template.start).split(splitRE)
const afterLines = output.split(splitRE).length
const templateLine = content.slice(0, parts.template.start).split(splitRE)
.length
for (; beforeLines < afterLines; beforeLines++) {
map.addMapping({
source: map._hashedFilename,
source: map._filename,
generated: {
line: beforeLines,
column: 0
Expand Down
4 changes: 2 additions & 2 deletions lib/compilers/coffee-compiler.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ const loadBabelConfig = require('../load-babel-config.js')

module.exports = function(raw, config, filePath) {
ensureRequire('coffee', ['coffeescript'])
var coffee = require('coffeescript')
var compiled
const coffee = require('coffeescript')
let compiled
try {
compiled = coffee.compile(raw, {
bare: true,
Expand Down
14 changes: 0 additions & 14 deletions lib/compilers/haml-compiler.js

This file was deleted.

14 changes: 0 additions & 14 deletions lib/compilers/jade-compiler.js

This file was deleted.

18 changes: 0 additions & 18 deletions lib/compilers/pug-compiler.js

This file was deleted.

14 changes: 7 additions & 7 deletions lib/ensure-require.js
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
const throwError = require('./throw-error')

module.exports = function(name, deps) {
var i, len
var missing = []
let i, len
let missing = []
if (typeof deps === 'string') {
deps = [deps]
}
for (i = 0, len = deps.length; i < len; i++) {
var mis
var req = deps[i]
let mis
let req = deps[i]
if (typeof req === 'string') {
mis = req
} else {
Expand All @@ -26,10 +26,10 @@ module.exports = function(name, deps) {
}
}
if (missing.length > 0) {
var message = 'You are trying to use "' + name + '". '
var npmInstall = 'npm install --save-dev ' + missing.join(' ')
let message = 'You are trying to use "' + name + '". '
let npmInstall = 'npm install --save-dev ' + missing.join(' ')
if (missing.length > 1) {
var last = missing.pop()
const last = missing.pop()
message += missing.join(', ') + ' and ' + last + ' are '
} else {
message += missing[0] + ' is '
Expand Down
22 changes: 12 additions & 10 deletions lib/generate-source-map.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,25 +4,27 @@ const splitRE = /\r?\n/g

module.exports = function generateSourceMap(
script,
output,
filePath,
content,
inputMap
) {
var hashedFilename = path.basename(filePath)
var map = new sourceMap.SourceMapGenerator()
map.setSourceContent(hashedFilename, content)
const filename = path.basename(filePath)

const map = new sourceMap.SourceMapGenerator()

map.setSourceContent(filename, content)
// check input source map from babel/coffee etc
var inputMapConsumer = inputMap && new sourceMap.SourceMapConsumer(inputMap)
var generatedOffset = (output ? output.split(splitRE).length : 0) + 1

let inputMapConsumer = inputMap && new sourceMap.SourceMapConsumer(inputMap)
const generatedOffset = 1
script.split(splitRE).forEach(function(line, index) {
var ln = index + 1
var originalLine = inputMapConsumer
let ln = index + 1
let originalLine = inputMapConsumer
? inputMapConsumer.originalPositionFor({ line: ln, column: 0 }).line
: ln
if (originalLine) {
map.addMapping({
source: hashedFilename,
source: filename,
generated: {
line: ln + generatedOffset,
column: 0
Expand All @@ -34,6 +36,6 @@ module.exports = function generateSourceMap(
})
}
})
map._hashedFilename = hashedFilename
map._filename = filename
return map
}
20 changes: 20 additions & 0 deletions lib/get-cache-key.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
const crypto = require('crypto')
const babelJest = require('babel-jest')

module.exports = function getCacheKey(
fileData,
filename,
configString,
{ instrument, rootDir }
) {
return crypto
.createHash('md5')
.update(
babelJest.getCacheKey(fileData, filename, configString, {
instrument,
rootDir
}),
'hex'
)
.digest('hex')
}
8 changes: 0 additions & 8 deletions lib/get_cache_key.js

This file was deleted.

98 changes: 63 additions & 35 deletions lib/process.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
const vueCompiler = require('vue-template-compiler')
const compileTemplate = require('./template-compiler')
const VueTemplateCompiler = require('vue-template-compiler')
const generateSourceMap = require('./generate-source-map')
const addTemplateMapping = require('./add-template-mapping')
const compileTypescript = require('./compilers/typescript-compiler')
Expand All @@ -12,6 +11,10 @@ const join = path.join
const logger = require('./logger')
const splitRE = /\r?\n/g
const babelJest = require('babel-jest')
const compilerUtils = require('@vue/component-compiler-utils')
const throwError = require('./throw-error')
const chalk = require('chalk')
const convertSourceMap = require('convert-source-map')

function processScript(scriptPart, filePath, config) {
if (!scriptPart) {
Expand All @@ -31,32 +34,44 @@ function processScript(scriptPart, filePath, config) {

module.exports = function(src, filePath, config) {
const vueJestConfig = getVueJestConfig(config)
let parts = vueCompiler.parseComponent(src, { pad: true })
let scriptSrc = src
const parts = compilerUtils.parse({
source: src,
compiler: VueTemplateCompiler,
filename: filePath
})
let scriptSrcContent = src
let sourceMapPath = filePath

if (parts.script && parts.script.src) {
const externalScrPath = join(filePath, '..', parts.script.src)

parts.script.content = fs.readFileSync(externalScrPath, 'utf8')
scriptSrc = parts.script.content
scriptSrcContent = parts.script.content
sourceMapPath = externalScrPath
}

const result = processScript(parts.script, filePath, config)
const script = result.code
let compiledScriptContent = result.code
compiledScriptContent = compiledScriptContent.slice(
0,
compiledScriptContent.indexOf('//# sourceMappingURL')
)
const inputMap = result.map

const map = generateSourceMap(script, '', sourceMapPath, scriptSrc, inputMap)

let output =
';(function(){\n' +
script +
'\n})()\n' +
'var defaultExport = (module.exports.__esModule) ? module.exports.default : module.exports;' +
'var __vue__options__ = (typeof defaultExport === "function"' +
'? defaultExport.options' +
': defaultExport)\n'
const map = generateSourceMap(
compiledScriptContent,
sourceMapPath,
scriptSrcContent,
inputMap
)

let output = `var exports = {}
${compiledScriptContent}
if(!exports.default) {
exports.default = {}
}
var __options__ = module.exports = exports.default
Object.keys(exports).forEach(k => module.exports[k] = exports[k])`

if (parts.template) {
parts.template.filename = filePath
Expand All @@ -65,24 +80,36 @@ module.exports = function(src, filePath, config) {
parts.template.content = fs.readFileSync(parts.template.filename, 'utf8')
}

const renderFunctions = compileTemplate(parts.template, vueJestConfig)
const templateResult = compilerUtils.compileTemplate({
source: parts.template.content,
compiler: VueTemplateCompiler,
filename: parts.template.filename,
isFunctional: parts.template.attrs.functional,
preprocessLang: parts.template.lang,
preprocessOptions: vueJestConfig[parts.template.lang]
})

if (templateResult.errors.length) {
templateResult.errors.forEach(function(msg) {
console.error('\n' + chalk.red(msg) + '\n')
})
throwError('Vue template compilation failed')
}

output +=
'__vue__options__.render = ' +
renderFunctions.render +
'\n' +
'__vue__options__.staticRenderFns = ' +
renderFunctions.staticRenderFns +
'\n'
output += `
${templateResult.code}
__options__.render = render
__options__.staticRenderFns = staticRenderFns
`

if (parts.template.attrs.functional) {
output += '__vue__options__.functional = true\n'
output += '__vue__options__._compiled = true\n'
output += '__options__.functional = true\n'
output += '__options__._compiled = true\n'
}

if (map) {
const beforeLines = output.split(splitRE).length
addTemplateMapping(script, parts, output, map, beforeLines)
addTemplateMapping(compiledScriptContent, parts, output, map, beforeLines)
}
}

Expand Down Expand Up @@ -118,12 +145,12 @@ module.exports = function(src, filePath, config) {
.join('')

if (styleStr.length !== 0) {
if (parts.template.attrs.functional) {
if (parts.template && parts.template.attrs.functional) {
output += `
;(function() {
var originalRender = __vue__options__.render
var originalRender = __options__.render
var styleFn = function () { ${styleStr} }
__vue__options__.render = function renderWithStyleInjection (h, context) {
__options__.render = function renderWithStyleInjection (h, context) {
styleFn.call(context)
return originalRender(h, context)
}
Expand All @@ -132,17 +159,18 @@ module.exports = function(src, filePath, config) {
} else {
output += `
;(function() {
var beforeCreate = __vue__options__.beforeCreate
var beforeCreate = __options__.beforeCreate
var styleFn = function () { ${styleStr} }
__vue__options__.beforeCreate = beforeCreate ? [].concat(beforeCreate, styleFn) : [styleFn]
__options__.beforeCreate = beforeCreate ? [].concat(beforeCreate, styleFn) : [styleFn]
})()
`
}
}
}

const base64Map = Buffer.from(JSON.stringify(map)).toString('base64')
output += `//# sourceMappingURL=data:application/json;charset=utf-8;base64,${base64Map}`
if (map) {
output += '\n' + convertSourceMap.fromJSON(map.toString()).toComment()
}

return { code: output }
return { code: output, map }
}
48 changes: 0 additions & 48 deletions lib/template-compiler.js

This file was deleted.

Loading