Ejemplo n.º 1
0
module.exports = function (source) {
  const SCRIPT = utils.stringifyRequest(this, scriptLoader).replace(/"/g, '')
  const STYLE = utils.stringifyRequest(this, styleLoader).replace(/"/g, '')
  const AFTER_LESS_STYLE = utils.stringifyRequest(this, afterLessLoader).replace(/"/g, '')
  const TEMPLATE = utils.stringifyRequest(this, templateLoader).replace(/"/g, '')
  const BEFORE_TEMPLATE_COMPILER = utils.stringifyRequest(this, beforeTemplateCompilerLoader).replace(/"/g, '')


  const variableMap = this.vuxVariableMap || utils.getLoaderConfig(this, 'vuxVariableMap')

  var query = this.query ? utils.parseQuery(this.query) : {}
  this.cacheable()
  if (!source) return source
  const config = this.vux || utils.getLoaderConfig(this, 'vux')
  if (!config) {
    return source
  }

  let variables = ''
  var themes = config.plugins.filter(function (plugin) {
    return plugin.name === 'less-theme'
  })

  if (themes.length) {
    const themePath = path.join(config.options.projectRoot, themes[0].path)
    this.addDependency(themePath)
    variables = getLessVariables(themes[0].path)
    for (let i in variables) {
      if (variableMap[i]) {
        variables[variableMap[i]] = variables[i]
        if (i !== variableMap[i]) {
          delete variables[i]
        }
      }
    }
  }

  source = addScriptLoader(source, SCRIPT)
  source = addStyleLoader(source, STYLE, variables, AFTER_LESS_STYLE)
  source = addTemplateLoader(source, TEMPLATE, BEFORE_TEMPLATE_COMPILER)

  // fix style path in dev mode
  if (config.options.vuxDev) {
    source = source.replace(/vux\/src\/styles\/(.*?)/g, '../styles/$1')
  }

  return source
}
Ejemplo n.º 2
0
module.exports = function (source) {
  this.cacheable()
  const _this = this
  const config = this.vux || utils.getLoaderConfig(this, 'vux')

  if (!config.plugins || !config.plugins.length) {
    return source
  }

  config.plugins.forEach(function (plugin) {
    // style-parser
    if (plugin.name === 'style-parser') {
      if (plugin.fn) {
        source = plugin.fn.call(_this, source)
      }
    }
  })

  if (config.options.vuxDev) {
    if (/App\.vue$/.test(this.resourcePath)) {
      source = source.replace(/~vux\/src/g, '.')
    } else {
      if (config.options.resolveVuxDir) {
        // if (_this.resourcePath.includes('pages') && _this.resourcePath.includes('IconLoading') )
        // source = source.replace(/~vux\/src/g, config.options.resolveVuxDir).replace('//', '/')
        // if (_this.resourcePath.includes('pages') && _this.resourcePath.includes('IconLoading') )
      } else {
        source = source.replace(/~vux\/src/g, '..')
      }
    }
  }

  return source
}
Ejemplo n.º 3
0
module.exports = function(content) {
  var callback = this.async();
  this.cacheable && this.cacheable();
  this.value = content;

  var config = Object.assign({
    extensions: ['.css'],
    resolveUrls: true,
    context: this.context
  }, loaderUtils.getLoaderConfig(this, 'cssConcat'));

  var url = loaderUtils.interpolateName(this, '[path][name].[ext]', {
    context: this.context,
    content: content
  });
  try {
    var result = parseImports(path.join(this.context, url), content, config);
    var cssAsString = JSON.stringify(result.css);
    cssAsString = cssAsString.replace(/___CSS_LOADER_URL___([0-9]+)___/g, function (match, id) {
      return 'url(\\"" + require("' + result.urls[id] + '") + "\\")';
    });
    callback(null, "module.exports = " + cssAsString);
  } catch (err) {
    callback(err);
  }

};
Ejemplo n.º 4
0
module.exports = function(content) {
  this.cacheable && this.cacheable();

  var config = loaderUtils.getLoaderConfig(this, "imageWebpackLoader");
  var options = {
    interlaced: config.interlaced || false,
    progressive: config.progressive || false,
    optimizationLevel: config.optimizationLevel || 3,
    bypassOnDebug: config.bypassOnDebug || false,
    pngquant: config.pngquant || false,
    svgo: config.svgo || {}
  };

  var callback = this.async(), called = false;

  if (this.debug === true && options.bypassOnDebug === true) {
    // Bypass processing while on watch mode
    return callback(null, content);
  } else {
    var imagemin = new Imagemin()
    .src(content)
    .use(Imagemin.gifsicle({
      interlaced: options.interlaced
    }))
    .use(Imagemin.jpegtran({
      progressive: options.progressive
    }))
    .use(Imagemin.svgo(options.svgo));

    if (options.pngquant) {
      imagemin.use(imageminPngquant(options.pngquant));
    } else {
      imagemin.use(Imagemin.optipng({
        optimizationLevel: options.optimizationLevel
      }));
    }

    imagemin.run(function(err, files) {
      if (called) {
        console.log("something is very odd, it is being called twice");
        return;
      }
      called = true;
      if (err) {
        callback(err);
      } else {
        callback(null, files[0].contents);
      }
    });
  }
};
Ejemplo n.º 5
0
module.exports = function(content) {
  this.cacheable && this.cacheable();

  var config = loaderUtils.getLoaderConfig(this, "imageWebpackLoader");
  var options = {
    interlaced: config.interlaced || false,
    optimizationLevel: config.optimizationLevel || 3,
    bypassOnDebug: config.bypassOnDebug || false,
    mozjpeg: config.mozjpeg || false,
    pngquant: config.pngquant || false,
    svgo: config.svgo || {}
  };

  var callback = this.async(),
    called = false;

  if (this.debug === true && options.bypassOnDebug === true) {
    // Bypass processing while on watch mode
    return callback(null, content);
  } else {
    var plugins = [];
    plugins.push(imageminGifsicle({
      interlaced: options.interlaced
    }));
    plugins.push(imageminMozjpeg(options.mozjpeg));
    plugins.push(imageminSvgo(options.svgo));
    plugins.push(imageminPngquant(options.pngquant));
    plugins.push(imageminOptipng({
      optimizationLevel: options.optimizationLevel
    }));

    imagemin
      .buffer(content, {
        plugins
      })
      .then(data => {
        callback(null, data);
      })
      .catch(err => {
        callback(err);
      });
  }
};
Ejemplo n.º 6
0
module.exports = function (source) {
  if (this.cacheable) this.cacheable()
  var callback = this.async()

  var config = loaderUtils.getLoaderConfig(this, 'uikitLoader')

  // Only act on uikit less imports by default
  var testPattern = config.test || /node_modules\/uikit\/.+less$/
  if (!testPattern.test(this.resourcePath)) {
    return callback(null, source)
  }

  var themeName = config.theme
  if (!themeName) {
    return callback(new Error('No `theme` specified in the uikit-loader options! See: https://github.com/stipsan/uikit-loader#usage'))
  }

  var themePath = path.resolve(themeName)

  var themeExists = fs.existsSync(themePath)
  if (!themeExists) {
    return callback(new Error(`The path ${themePath} does not exist!`))
  }

  this.addDependency(themePath)

  var prepend = config.prepend || false

  var relativePath = path.relative(this.context, themePath)
  var theme = `@import "${relativePath}";`

  var compiled = source
  if (prepend) {
    compiled = theme + '\n' + compiled
  } else {
    compiled = compiled + '\n' + theme
  }
  callback(null, compiled)
}
module.exports = function (source) {
  this.cacheable()
  const _this = this
  const config = this.vux || utils.getLoaderConfig(this, 'vux')

  if (!config.plugins || !config.plugins.length) {
    return source
  }

  if (config.options.useVuxUI && source.indexOf('</x-icon>') > -1) {
    source = parseXIcon(source, config)
  }

  config.plugins.forEach(function (plugin) {
    // style-parser
    if (plugin.name === 'before-template-compiler-parser') {
      if (plugin.fn) {
        source = plugin.fn.call(_this, source)
      }
    }
  })

  return source
}
module.exports = function(source) {
  var self = this
  if (self.cacheable) self.cacheable()
  var configPaths = cloneDeep(loaderUtils.getLoaderConfig(self, "multiStylusLoader")).paths
  var context = self.context
  var done = self.async()

  getConfigs(configPaths).then(function(configs) {
    return mutliRender(source, configs)
  }).then(function (results) {
    var output = results
    done(null, output)
  }).catch(function (err) {
    done(err)
  })

  function mutliRender (source, configs) {
    return Promise.all(
      Object.keys(configs).map(function(namespace, index) {
        var currentNamespace = namespace
        thisSource = '.' + namespace + '\n' 
          + indentSource(source, 2)
        var config = configs[namespace]
        return renderPromise(thisSource, config)
          .then(function(result) {
            result = '\n/* ' + currentNamespace + ' */\n' + result
            return result
          })
      })
    ).then(function(results) {
      return results.join('\n\n')
    })
  }

  function getConfigs (configPaths) {
    return Promise.all(
      Object.keys(configPaths).map(function(configName) {
        var configPath = configPaths[configName]
        // Asynchronously load import
        var configFileName
        return resolvePromise(context, configPath)
          .then(function(fileName) {
            self.addDependency && self.addDependency(fileName)
            configFileName = fileName
            return loadModulePromise('-!' + __dirname + '/identity.loader.js!' + fileName)
          }).then(function (results) {
            results = self.exec(results, configFileName)
            configPaths[configName] = results
          }).catch(function(err) {
            console.log('load module promise err', err)
          })
      })
    ).then(function () {
      return configPaths
    })
  }

  function renderPromise (source, config, namespace) {
    return new Promise(function(resolve, reject) {
      var compiler = stylus(source)
      applyOptions(compiler, config)
      compiler.render(function(err, css) {
        if (err) reject(err)
        resolve(css)
      })
    })
  }

  function resolvePromise(context, request) {
    return new Promise(function (resolve, reject) {
      self.resolve(context, request, function(err, filename) {
        if (err) reject(err)
        resolve(filename)
      })
    })
  }

  function loadModulePromise(request) {
    return new Promise(function (resolve, reject) {
      self.loadModule(request, function(err, source) {
        if (err) reject(err)
        resolve(source)
      })
    })
  }

  function applyOptions(stylus, options) {
    ['set', 'include', 'import', 'define', 'use'].forEach(function(method) {
      var option = options[method]
      if (isArray(option)) {
        for (var i = 0; i < option.length; i++) {
          stylus[method](option[i])
          if ('include' === method) {
            self.addContextDependency(option[i])
          }
        }
      } else {
        for (var prop in option)
          stylus[method](prop, option[prop])
      }
    })
  }
}
Ejemplo n.º 9
0
/**
 * Initialize the loader with web3 and config
 */
function init(loader) {
  var loaderConfig = loaderUtils.getLoaderConfig(loader, 'web3Loader');
  web3 = require('./lib/web3')(loaderConfig.provider);
  config = mergeConfig(loaderConfig);
  isDebug = loader.debug;
}
Ejemplo n.º 10
0
module.exports = function (source) {
  this.cacheable()
  const _this = this
  const config = this.vux || utils.getLoaderConfig(this, 'vux')
  if (!config.plugins || !config.plugins.length) {
    return source
  }

  let i18nPlugin
  const i18nPluginsMatch = config.plugins.filter(function (one) {
    return one.name === 'i18n'
  })
  if (i18nPluginsMatch.length) {
    i18nPlugin = i18nPluginsMatch[0]
  }
  let isVuxVueFile = this.resourcePath.replace(/\\/g, '/').indexOf('vux/src/components') > -1
  if (config.options.vuxDev && this.resourcePath.replace(/\\/g, '/').indexOf('src/components') > -1) {
    isVuxVueFile = true
  }

  const isVuxComponent = this.resourcePath.replace(/\\/g, '/').indexOf('/vux/src/components') > -1

  if (config.plugins.length) {
    config.plugins.forEach(function (plugin) {
      // script-parser
      if (plugin.name === 'script-parser') {
        if (plugin.fn) {
          source = plugin.fn.call(_this, source)
        }
      }
    })
  }

  if (config.options.useVuxUI && /}\s+from(.*?)('|")vux/.test(source)) {
    const maps = this.vuxMaps || utils.getLoaderConfig(this, 'vuxMaps')
    const parser = require('./libs/import-parser')
    source = parser(source, function (opts) {
      let str = ''
      opts.components.forEach(function (component) {
        let file = `vux/${maps[component.originalName]}`
        if (config.options.vuxDev) {
          if (/App\.vue/.test(_this.resourcePath)) {
            file = file.replace(/vux\/src/g, '.')
          } else {
            let relative = '..'
            // component file import other functions
            if (isVuxComponent && !/components/.test(file)) {
              relative = '../..'
            }

            if (/demos/.test(_this.resourcePath)) {
              const splits = _this.resourcePath.split('demos')[1].split(path.sep).length - 1
              let dir = []
              for (let i = 0; i < splits; i++) {
                dir.push('..')
              }
              relative = dir.join('/')
            }

            if (config.options.resolveVuxDir) {
              relative = config.options.resolveVuxDir
            }

            file = file.replace(/vux\/src/g, relative)
          }
        }
        str += `import ${component.newName} from '${file}'\n`
      })
      return str
    }, 'vux')
  }

  if (config.options.vuxWriteFile === true) {
    fs.writeFileSync(this.resourcePath + '.vux.js', source)
  }

  if (i18nPlugin && !isVuxVueFile && source.indexOf(`$t('`) > -1 && i18nPlugin.staticReplace === true) {
    const rs = getI18nBlockWithLocale({
      code: _this.resourcePath,
      isFile: true,
      locale: i18nPlugin.vuxLocale || 'zh-CN'
    })
    source = i18nReplaceForScript(source, rs)
  }

  return source
}
Ejemplo n.º 11
0
module.exports = function (content) {
  const isWebpack2 = !!this.remainingRequest;
  const callback = this.async();
  const config = loaderUtils.getLoaderConfig(this, 'imageOptimizeLoader') || {};

  const fileName = this.request.split('!').pop();
  const fileHash = getHashOf(content);
  const fileExt = path.extname(fileName).replace(/^./, '');
  let cacheKey = getHashOf(fileName);

  // extend default configs
  const settings = {};

  settings.optimizer = Object.assign({},
    defaultSettings.optimizer,
    config.optimizer || {});

  settings.mozjpeg = Object.assign({},
    settings.optimizer,
    defaultSettings.mozjpeg,
    config.mozjpeg || {});

  settings.pngquant = Object.assign({},
    settings.optimizer,
    defaultSettings.pngquant,
    config.pngquant || {});

  settings.svgo = Object.assign({},
    settings.optimizer,
    defaultSettings.svgo,
    config.svgo || {});

  // add settings to cacheKey by extension
  switch (fileExt) {
  case 'png':
    cacheKey = getHashOf(JSON.stringify([cacheKey, settings.pngquant, isWebpack2]));
    break;
  case 'jpg':
    cacheKey = getHashOf(JSON.stringify([cacheKey, settings.mozjpeg]));
    break;
  case 'svg':
    cacheKey = getHashOf(JSON.stringify([cacheKey, settings.svgo]));
    break;
  default:
    break;
  }

  const promiseOptimizeImage = Q.defer();
  const promisePrepareImage = Q.defer();
  const checkCacheExists = Q.defer();


  function startOptimization() {
    asyncQueue.addTask(function () {
      // concurrency++;
      // console.log(`\r optimize:start ${concurrency}`);

      const completePromise = Q.defer();
      promisePrepareImage.resolve(completePromise);
      completePromise.promise.then(this.wrapCallback(() => {
        // concurrency--;
        // console.log(`\r optimize:finished ${concurrency}`);
      }))
      .catch(callback);
    });
  }

  // ensure cache exists
  checkCacheExists.promise.then(() => {
    Q.all([
      cache.has(cacheKey).catch(callback),
      cache.has(`${cacheKey}-checksum`).catch(callback),
    ]).then(checks => {
      // if cache is not found
      if (!checks[0] || !checks[1]) {
        startOptimization();
        return;
      }

      // check is cache up to date
      cache.get(`${cacheKey}-checksum`).then(results => {
        const data = JSON.parse(results.value);

          // if file not changed, return cached value
        if (data.fileHash === fileHash) {
          cache.get(cacheKey).then(cacheEntry => {
            this.resource = data.resource;
            promisePrepareImage.reject();
            return callback(null, cacheEntry.value);
          }).catch(callback);

          // cache is outdated, create new image
        } else {
          startOptimization();
        }
      }).catch(callback);
    }).catch(callback);
  }).catch(callback);

  promisePrepareImage.promise.then((completePromise) => {
    if (settings.optimizer.covertPngToJpg && fileExt === 'png' && isWebpack2) {
      streamifier.createReadStream(content)
        .pipe(new PNG())
        .on('metadata', data => {
          if (data.alpha) {
            return promiseOptimizeImage.resolve(completePromise);
          }

          // if alpha not found - convert buffer to jpg
          gm(content).toBuffer('JPG', (err, buffer) => {
            if (err) {
              return callback(err);
            }

            this.resource = this.resource.replace(/.png$/, '.jpg');
            content = buffer;
            promiseOptimizeImage.resolve(completePromise);

            return false;
          });

          return false;
        });
    } else {
      promiseOptimizeImage.resolve(completePromise);
    }
  }).catch(callback);

  promiseOptimizeImage.promise.then((completePromise) => {
    imagemin.buffer(content, {
      plugins: [
        imageminMozjpeg(settings.mozjpeg),
        imageminPngquant(settings.pngquant),
        imageminSvgo(settings.svgo),
      ],
    }).then(file => {
      cache.set(cacheKey, file);
      cache.set(`${cacheKey}-checksum`, JSON.stringify({
        fileHash,
        resource: this.resource,
      }));

      completePromise.resolve();
      callback(null, file);
    }).catch(callback);
  }).catch(callback);

  checkCacheExists.resolve();
};