All files loader.js

86.21% Statements 25/29
72.41% Branches 21/29
100% Functions 4/4
86.21% Lines 25/29

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78        1x 44x   44x 24x   20x     1x 24x           24x           12x 12x 12x 12x 12x 12x   12x   12x       12x 12x 12x         12x         1x                                     12x 12x   12x   12x    
import { getOptions } from 'loader-utils'
import validateOptions from 'schema-utils'
import { URL } from 'url'
 
const isURLInstance = str => {
  try {
    // eslint-disable-next-line no-new
    new URL(str)
    return true
  } catch (err) {
    return false
  }
}
const isURL = str => {
  Eif (
    isURLInstance(str) ||
    isURLInstance(`http:/${str}`) ||
    isURLInstance(`http://${str}`) ||
    isURLInstance(`http:/${str.replace('./', '/')}`)
  ) {
    return true
  }
  return false
}
 
function processSource(source, options = {}) {
  const fromURL = options.from
  const toURL = options.to
  const mode = options.mode || 'production'
  const env = options.env || 'production'
  const NODE_ENV = (process.env && process.env.NODE_ENV) || ''
  const WEBPACK_MODE = (process.env && process.env.WEBPACK_MODE) || ''
 
  Iif (!fromURL || !toURL) {
    throw new Error(`Must set 'from' and 'to' options!`)
  } else Iif (!isURL(fromURL) || !isURL(toURL)) {
    throw new Error(`Cannot transform ${options.from} to ${options.to}!`)
  }
 
  Eif (NODE_ENV === env || WEBPACK_MODE === mode) {
    const escapedFromURL = fromURL.replace(/\//g, '\\/')
    const newSource = source
      .replace(new RegExp(`url\\(\\s*${escapedFromURL}`, 'g'), `url(${toURL}`)
      .replace(new RegExp(`url\\(\\s*'${escapedFromURL}`, 'g'), `url('${toURL}`)
      .replace(new RegExp(`url\\(\\s*"${escapedFromURL}`, 'g'), `url("${toURL}`)
 
    return newSource
  }
  return source
}
 
const schema = {
  type: 'object',
  properties: {
    from: {
      type: 'string',
    },
    to: {
      type: 'string',
    },
    mode: {
      type: 'string',
    },
    env: {
      type: 'string',
    },
  },
}
 
export default function loader(source) {
  const options = getOptions(this)
  validateOptions(schema, options, 'css-url-loader')
 
  const processedSource = processSource(source, options)
 
  return processedSource
}