Skip to content

add pre & post css transform callbacks to customize css transformatio… #146

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 2 commits into from
Jan 26, 2019
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: 6 additions & 0 deletions e2e/__projects__/babel-config/__snapshots__/test.js.snap
Original file line number Diff line number Diff line change
Expand Up @@ -140,3 +140,9 @@ __options__.staticRenderFns = staticRenderFns

//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJzb3VyY2VzIjpbIkJhc2ljU3JjLmpzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7Ozs7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBQ0E7QUFDQTtBQUhBO0FBS0E7QUFQQTtBQVNBO0FBQ0E7QUFDQTtBQUNBO0FBRkE7QUFJQTtBQUNBO0FBQ0E7QUFDQTtBQUNBO0FBSEE7QUFqQkEiLCJzb3VyY2VzQ29udGVudCI6WyJleHBvcnQgZGVmYXVsdCB7XG4gIG5hbWU6ICdiYXNpYycsXG4gIGNvbXB1dGVkOiB7XG4gICAgaGVhZGluZ0NsYXNzZXM6IGZ1bmN0aW9uIGhlYWRpbmdDbGFzc2VzKCkge1xuICAgICAgcmV0dXJuIHtcbiAgICAgICAgcmVkOiB0aGlzLmlzQ3JhenksXG4gICAgICAgIGJsdWU6ICF0aGlzLmlzQ3JhenksXG4gICAgICAgIHNoYWRvdzogdGhpcy5pc0NyYXp5XG4gICAgICB9XG4gICAgfVxuICB9LFxuICBkYXRhOiBmdW5jdGlvbiBkYXRhKCkge1xuICAgIHJldHVybiB7XG4gICAgICBtc2c6ICdXZWxjb21lIHRvIFlvdXIgVnVlLmpzIEFwcCcsXG4gICAgICBpc0NyYXp5OiBmYWxzZVxuICAgIH1cbiAgfSxcbiAgbWV0aG9kczoge1xuICAgIHRvZ2dsZUNsYXNzOiBmdW5jdGlvbiB0b2dnbGVDbGFzcygpIHtcbiAgICAgIHRoaXMuaXNDcmF6eSA9ICF0aGlzLmlzQ3JhenlcbiAgICB9XG4gIH1cbn1cbiJdfQ=="
`;

exports[`processes PostCSS 1`] = `"<section><div></div> <div class=\\"red\\"></div></section>"`;

exports[`processes SCSS using user specified post transforms 1`] = `"<div class=\\"testA\\"><span class=\\"g\\"></span> <span class=\\"f\\"></span></div>"`;

exports[`processes SCSS using user specified pre transforms 1`] = `"<div class=\\"testA\\"><span class=\\"g\\"></span> <span class=\\"f\\"></span></div>"`;
5 changes: 5 additions & 0 deletions e2e/__projects__/babel-config/babel-transformer.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
const { createTransformer } = require('babel-jest')
module.exports = createTransformer({
presets: ['@babel/preset-env'],
plugins: ['transform-vue-jsx']
})
17 changes: 7 additions & 10 deletions e2e/__projects__/babel-config/components/PostCss.vue
Original file line number Diff line number Diff line change
@@ -1,21 +1,18 @@
<template>
<div :class="$style.testPcss"></div>
<section>
<div :class="$style.testPcss"></div>
<div :class="$style.red"></div>
</section>
</template>

<style lang="postcss">
.testPcss {
background-color: purple;
background: color(purple a(90%));
}
</style>

<style module lang="pcss">
/* This syntax is for postcss-custom-properties */
--primary-color: green;

/* This syntax is for postcss-nesting, but invalid as Pure CSS */
body {
@media screen {
background-color: grey;
}
.red {
background: color(red a(90%));
}
</style>
5 changes: 5 additions & 0 deletions e2e/__projects__/babel-config/components/Sass.vue
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,8 @@
.d
background-color: blue
</style>

<style lang="sass" module themed>
.e
background-color: blue
</style>
11 changes: 10 additions & 1 deletion e2e/__projects__/babel-config/components/Scss.vue
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
<template>
<div class="testA"></div>
<div class="testA">
<span :class="this.$style.g"></span>
<span :class="this.$style.dark.f"></span>
</div>
</template>

<style module lang="scss">
Expand All @@ -15,3 +18,9 @@
background-color: red;
}
</style>

<style lang="scss" module themed>
.f {
background-color: red;
}
</style>
7 changes: 7 additions & 0 deletions e2e/__projects__/babel-config/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@
"babel-plugin-transform-vue-jsx": "^3.7.0",
"jest": "^23.6.0",
"node-sass": "^4.11.0",
"postcss": "^7.0.13",
"postcss-color-function": "^4.0.1",
"vue-jest": "file:../../../"
},
"jest": {
Expand All @@ -40,6 +42,11 @@
"vue-jest": {
"pug": {
"basedir": "./"
},
"transform": {
"^scss$": "./scssTransform.js",
"^pcss|postcss$": "./pcssTransform.js",
"^js$": "./babel-transformer.js"
}
}
}
Expand Down
7 changes: 7 additions & 0 deletions e2e/__projects__/babel-config/pcssTransform.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
const postcss = require('postcss')
var colorFunction = require('postcss-color-function')
module.exports = {
process: function(content, filepath, config, attrs) {
return postcss([colorFunction()]).process(content).css
}
}
21 changes: 21 additions & 0 deletions e2e/__projects__/babel-config/scssTransform.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
const cssExtract = require('extract-from-css')
module.exports = {
postProcess: function postProcess(src, filepath, config, attrs) {
const cssNames = cssExtract.extractClasses(src)
const obj = {}
for (let i = 0, l = cssNames.length; i < l; i++) {
obj[cssNames[i]] = cssNames[i]
}

if (attrs.themed) {
return {
light: obj,
dark: obj
}
}
return obj
},
preProcess: function postProcess(src, filepath, config, attrs) {
return `${src}\n .g{width: 10px}`
}
}
21 changes: 20 additions & 1 deletion e2e/__projects__/babel-config/test.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import Constructor from './components/Constructor.vue'

test('processes .vue files', () => {
const wrapper = mount(Basic)
expect(wrapper.vm.msg).toEqual('Welcome to Your Vue.js App')
wrapper.vm.toggleClass()
})

Expand Down Expand Up @@ -119,7 +120,9 @@ it('processes Less', () => {

it('processes PostCSS', () => {
const wrapper = mount(PostCss)
expect(wrapper.is('div')).toBeTruthy()
expect(wrapper.is('section')).toBeTruthy()
expect(wrapper.vm.$style.red).toEqual('red')
expect(wrapper.html()).toMatchSnapshot()
})

test('processes pug templates', () => {
Expand All @@ -145,6 +148,7 @@ it('processes Sass', () => {
expect(wrapper.vm.$style.a).toEqual('a')
expect(wrapper.vm.$style.b).toEqual('b')
expect(wrapper.vm.$style.c).toEqual('c')
expect(wrapper.vm.$style.light).toBeUndefined()
})

it('processes SCSS', () => {
Expand All @@ -154,6 +158,21 @@ it('processes SCSS', () => {
expect(wrapper.vm.$style.c).toEqual('c')
})

test('processes SCSS using user specified post transforms', () => {
const wrapper = mount(Scss)
expect(wrapper.vm.$style.light.a).toBeUndefined()
expect(wrapper.vm.$style.light.f).toEqual('f')
expect(wrapper.vm.$style.dark.f).toEqual('f')
expect(wrapper.vm.$style.dark.g).toEqual('g')
expect(wrapper.html()).toMatchSnapshot()
})

test('processes SCSS using user specified pre transforms', () => {
const wrapper = mount(Scss)
expect(wrapper.vm.$style.g).toEqual('g')
expect(wrapper.html()).toMatchSnapshot()
})

test('process Stylus', () => {
const wrapper = mount(Stylus)
expect(wrapper.vm).toBeTruthy()
Expand Down
2 changes: 1 addition & 1 deletion e2e/test-runner.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,7 +43,7 @@ function runTest(dir) {
run('npm install --silent')

log('Running tests')
run('npm run test')
run('npm run test')

success(`(${dir}) Complete`)
}
Expand Down
25 changes: 16 additions & 9 deletions lib/compilers/helpers/module-name-mapper-helper.js
Original file line number Diff line number Diff line change
@@ -1,17 +1,22 @@
const path = require('path')

const matchModuleImport = /^[^?]*~/
/**
* Resolves the path to the file locally.
* Resolves the path to the file/module.
*
* @param {String} to - the name of the file to resolve to
* @param {String} localPath - the local path
* @param {String} importPath - the local path
* @param {String} fileType - extension of the file to be resolved
* @returns {String} path - path to the file to import
*/
function localResolve(to, localPath) {
if (localPath.startsWith('/')) {
return localPath
function resolve(to, importPath, fileType) {
importPath =
path.extname(importPath) === '' ? `${importPath}.${fileType}` : importPath
if (importPath.startsWith('/')) {
return importPath
} else if (matchModuleImport.test(importPath)) {
return require.resolve(importPath.replace(matchModuleImport, ''))
}
return path.join(path.dirname(to), localPath)
return path.join(path.dirname(to), importPath)
}

/**
Expand All @@ -20,12 +25,14 @@ function localResolve(to, localPath) {
* @param {String} source - the original string
* @param {String} filePath - the path of the current file (where the source originates)
* @param {Object} jestConfig - the jestConfig holding the moduleNameMapper settings
* @param {Object} fileType - extn of the file to be resolved
* @returns {String} path - the final path to import (including replacements via moduleNameMapper)
*/
module.exports = function applyModuleNameMapper(
source,
filePath,
jestConfig = {}
jestConfig = {},
fileType = ''
) {
if (!jestConfig.moduleNameMapper) return source

Expand All @@ -47,5 +54,5 @@ module.exports = function applyModuleNameMapper(
)
}, source)

return localResolve(filePath, importPath)
return resolve(filePath, importPath, fileType)
}
3 changes: 2 additions & 1 deletion lib/compilers/sass-compiler.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ module.exports = (content, filePath, jestConfig = {}) => {
file: applyModuleNameMapper(
url,
prev === 'stdin' ? filePath : prev,
jestConfig
jestConfig,
'sass'
)
})
})
Expand Down
17 changes: 3 additions & 14 deletions lib/compilers/scss-compiler.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
const path = require('path')
const fs = require('fs')
const ensureRequire = require('../ensure-require')
const getVueJestConfig = require('../utils').getVueJestConfig
const warn = require('../utils').warn
Expand All @@ -19,26 +17,17 @@ module.exports = (content, filePath, jestConfig = {}) => {

ensureRequire('scss', ['node-sass'])
const sass = require('node-sass')

let scssResources = ''
if (vueJestConfig.resources && vueJestConfig.resources.scss) {
scssResources = vueJestConfig.resources.scss
.map(scssResource => path.resolve(process.cwd(), scssResource))
.filter(scssResourcePath => fs.existsSync(scssResourcePath))
.map(scssResourcePath => fs.readFileSync(scssResourcePath).toString())
.join('\n')
}

try {
return sass
.renderSync({
data: scssResources + content,
data: content,
outputStyle: 'compressed',
importer: (url, prev, done) => ({
file: applyModuleNameMapper(
url,
prev === 'stdin' ? filePath : prev,
jestConfig
jestConfig,
'scss'
)
})
})
Expand Down
18 changes: 12 additions & 6 deletions lib/compilers/typescript-compiler.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,16 @@ const babelJest = require('babel-jest')
const getBabelOptions = require('../utils').getBabelOptions
const getTsJestConfig = require('../utils').getTsJestConfig
const stripInlineSourceMap = require('../utils').stripInlineSourceMap
const getCustomTransformer = require('../utils').getCustomTransformer
const getVueJestConfig = require('../utils').getVueJestConfig

module.exports = function compileTypescript(scriptContent, filePath, config) {
ensureRequire('typescript', ['typescript'])
const typescript = require('typescript')

const { tsconfig } = getTsJestConfig(config)
const vueJestConfig = getVueJestConfig(config)
const {
tsconfig
} = getTsJestConfig(config)
const babelOptions = getBabelOptions(filePath)

const res = typescript.transpileModule(scriptContent, tsconfig)
Expand All @@ -26,10 +30,12 @@ module.exports = function compileTypescript(scriptContent, filePath, config) {
plugins: [require('@babel/plugin-transform-modules-commonjs')]
}
}

const transformer = babelJest.createTransformer(
Object.assign(inlineBabelOptions, { inputSourceMap })
const customTransformer = getCustomTransformer(vueJestConfig['transform'], 'js');
const transformer = customTransformer.process ? customTransformer : babelJest.createTransformer(
Object.assign(inlineBabelOptions, {
inputSourceMap
})
)

return transformer.process(res.outputText, filePath, config)
}
}
Loading