webpack.config.js 2.0 KB

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