Skip to content

Instantly share code, notes, and snippets.

@yutahaga
Created December 7, 2018 14:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yutahaga/55f9ba1982ded618798d4345b6300f04 to your computer and use it in GitHub Desktop.
Save yutahaga/55f9ba1982ded618798d4345b6300f04 to your computer and use it in GitHub Desktop.
SCSS に JavaScript の変数を読み込む関数を追加する(Tailwind.css)。 参考: https://itnext.io/sharing-variables-between-js-and-sass-using-webpack-sass-loader-713f51fa7fa0
const config = require('./tailwind')
module.exports = {
'config($keys)': function(keys) {
const sass = require('node-sass')
const sassUtils = require('node-sass-utils')(sass)
const convertStringToSassDimension = function(result) {
// Only attempt to convert strings
if (typeof result !== 'string') {
return result
}
const cssUnits = [
'rem',
'em',
'vh',
'vw',
'vmin',
'vmax',
'ex',
'%',
'px',
'cm',
'mm',
'in',
'pt',
'pc',
'ch'
]
const parts = result.match(/[a-zA-Z]+|[0-9]+/g)
const value = parts[0]
const unit = parts[parts.length - 1]
if (cssUnits.indexOf(unit) !== -1) {
result = new sassUtils.SassDimension(parseInt(value, 10), unit)
}
return result
}
keys = keys.getValue().split('.')
let result = config
let i
for (i = 0; i < keys.length; i++) {
result = result[keys[i]]
if (typeof result === 'string') {
result = convertStringToSassDimension(result)
} else if (typeof result === 'object') {
Object.keys(result).forEach(function(key) {
const value = result[key]
result[key] = convertStringToSassDimension(value)
})
}
}
result = sassUtils.castToSass(result)
return result
}
}
@yutahaga
Copy link
Author

yutahaga commented Dec 7, 2018

node-sass-utils のインストールが必要。
node-sass を読み込むタイミングは関数内でなければならないので編集する場合は注意。

Nuxt.js の場合は nuxt.config.js で下記のように設定すれば良い。

build: {
  loaders: {
    scss: {
      functions: require('./scss-functions')
    }
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment