index.js 2.2 KB
/*
  MIT License http://www.opensource.org/licenses/mit-license.php
  Author Tobias Koppers @sokra
  Modified by Evan You @yyx990803
*/
var loaderUtils = require('loader-utils')
var path = require('path')
var hash = require('hash-sum')

module.exports = function () {}

module.exports.pitch = function (remainingRequest) {
  if (this.cacheable) this.cacheable()

  var isServer = this.options.target === 'node'
  var isProduction = this.minimize || process.env.NODE_ENV === 'production'
  var addStylesClientPath = loaderUtils.stringifyRequest(this, '!' + path.join(__dirname, 'lib/addStylesClient.js'))
  var addStylesServerPath = loaderUtils.stringifyRequest(this, '!' + path.join(__dirname, 'lib/addStylesServer.js'))

  var request = loaderUtils.stringifyRequest(this, '!!' + remainingRequest)
  var id = JSON.stringify(hash(request))

  var shared = [
    '// style-loader: Adds some css to the DOM by adding a <style> tag',
    '',
    '// load the styles',
    'var content = require(' + request + ');',
    // content list format is [id, css, media, sourceMap]
    "if(typeof content === 'string') content = [[module.id, content, '']];",
    'if(content.locals) module.exports = content.locals;'
  ]

  if (!isServer) {
    // on the client: dynamic inject + hot-reload
    return shared.concat([
      '// add the styles to the DOM',
      'var update = require(' + addStylesClientPath + ')(' + id + ', content, ' + isProduction + ');',
      '// Hot Module Replacement',
      'if(module.hot) {',
      ' // When the styles change, update the <style> tags',
      ' if(!content.locals) {',
      '   module.hot.accept(' + request + ', function() {',
      '     var newContent = require(' + request + ');',
      "     if(typeof newContent === 'string') newContent = [[module.id, newContent, '']];",
      '     update(newContent);',
      '   });',
      ' }',
      ' // When the module is disposed, remove the <style> tags',
      ' module.hot.dispose(function() { update(); });',
      '}'
    ]).join('\n')
  } else {
    // on the server: attach to Vue SSR context
    return shared.concat([
      '// add CSS to SSR context',
      'require(' + addStylesServerPath + ')(' + id + ', content, ' + isProduction + ');'
    ]).join('\n')
  }
}