index.js 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Tobias Koppers @sokra
  4. */
  5. var path = require("path");
  6. var loaderUtils = require("loader-utils");
  7. module.exports = function(content) {
  8. this.cacheable && this.cacheable();
  9. if(!this.emitFile) throw new Error("emitFile is required from module system");
  10. var query = loaderUtils.getOptions(this) || {};
  11. var configKey = query.config || "fileLoader";
  12. var options = this.options[configKey] || {};
  13. var config = {
  14. publicPath: undefined,
  15. useRelativePath: false,
  16. name: "[hash].[ext]"
  17. };
  18. // options takes precedence over config
  19. Object.keys(options).forEach(function(attr) {
  20. config[attr] = options[attr];
  21. });
  22. // query takes precedence over config and options
  23. Object.keys(query).forEach(function(attr) {
  24. config[attr] = query[attr];
  25. });
  26. var context = config.context || this.options.context;
  27. var url = loaderUtils.interpolateName(this, config.name, {
  28. context: context,
  29. content: content,
  30. regExp: config.regExp
  31. });
  32. var outputPath = "";
  33. var filePath = this.resourcePath;
  34. if (config.useRelativePath) {
  35. var issuerContext = this._module && this._module.issuer && this._module.issuer.context || context;
  36. var relativeUrl = issuerContext && path.relative(issuerContext, filePath).split(path.sep).join("/");
  37. var relativePath = relativeUrl && path.dirname(relativeUrl) + "/";
  38. if (~relativePath.indexOf("../")) {
  39. outputPath = path.posix.join(outputPath, relativePath, url);
  40. } else {
  41. outputPath = relativePath + url;
  42. }
  43. url = relativePath + url;
  44. } else if (config.outputPath) {
  45. // support functions as outputPath to generate them dynamically
  46. outputPath = (
  47. typeof config.outputPath === "function"
  48. ? config.outputPath(url)
  49. : config.outputPath + url
  50. );
  51. url = outputPath;
  52. } else {
  53. outputPath = url;
  54. }
  55. var publicPath = "__webpack_public_path__ + " + JSON.stringify(url);
  56. if (config.publicPath !== undefined) {
  57. // support functions as publicPath to generate them dynamically
  58. publicPath = JSON.stringify(
  59. typeof config.publicPath === "function"
  60. ? config.publicPath(url)
  61. : config.publicPath + url
  62. );
  63. }
  64. if (query.emitFile === undefined || query.emitFile) {
  65. this.emitFile(outputPath, content);
  66. }
  67. return "module.exports = " + publicPath + ";";
  68. };
  69. module.exports.raw = true;