webpack.config.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. const path = require('path');
  2. const VirtualModulesPlugin = require('../..');
  3. const swaggerJsDoc = require('swagger-jsdoc');
  4. function SwaggerPlugin() {}
  5. SwaggerPlugin.prototype.apply = function(compiler) {
  6. const pkgJsonModule = './package.json';
  7. const pkgJsonPath = require.resolve(pkgJsonModule);
  8. const pkgJson = require(pkgJsonModule);
  9. // Create some mock data for the virtual module
  10. const info = {
  11. title: pkgJson.name, version: pkgJson.version, description: pkgJson.description
  12. };
  13. // Creating an absolute path for 'swagger.json'
  14. // Webpack will look up 'swagger.json' by this path
  15. const swaggerJsonPath = path.join(path.dirname(pkgJsonPath), 'node_modules', 'swagger.json');
  16. // Creating a virtual module 'swagger.json' with initial content
  17. const virtualModules = new VirtualModulesPlugin({[swaggerJsonPath]: JSON.stringify({
  18. openapi: '3.0.0',
  19. info: info
  20. })});
  21. // Applying a webpack compiler to the virtual module
  22. virtualModules.apply(compiler);
  23. // Adding a webpack hook to create new virtual module with swaggerJsDoc() at compile time
  24. // Consult Swagger UI documentation for the settings passed to swaggerJsDoc()
  25. compiler.hooks.compilation.tap('SwaggerPlugin', function(compilation) {
  26. try {
  27. const swaggerJson = swaggerJsDoc({
  28. swaggerDefinition: {
  29. openapi: '3.0.0',
  30. info: info
  31. },
  32. apis: ['*.js', '!(node_modules)/**/*.js']
  33. });
  34. // Write new data to the virtual file at compile time
  35. virtualModules.writeModule(swaggerJsonPath, JSON.stringify(swaggerJson));
  36. } catch (e) {
  37. compilation.errors.push(e);
  38. }
  39. });
  40. };
  41. module.exports = {
  42. entry: './index.js',
  43. plugins: [new SwaggerPlugin()],
  44. module: {
  45. rules: [
  46. {
  47. test: /\.css$/,
  48. use: ['style-loader', 'css-loader']
  49. }
  50. ]
  51. }
  52. };