const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
const { peerDependencies } = require('./package.json');
const loaders = require('./webpack/loaders');
const basePlugins = require('./webpack/plugins');

const isDocsBuild = process.env.DOCS === 'true';
const isDevBuild = process.env.NODE_ENV === 'development';

const docsPlugins = isDocsBuild || isDevBuild ?
  [new HtmlWebpackPlugin({ template: '!!html-loader?minimize=false!index.html' })] :
  [];

if (isDocsBuild) {
  // Create a report about the generated JS bundles.
  docsPlugins.push(
    new BundleAnalyzerPlugin({
      openAnalyzer: false,
      analyzerMode: 'static',
    }));
}

module.exports = {
  // This is where we start to crawl the tree looking for imports to
  // tell us what the output bundle should include.
  entry: './src/index.js',

  // This is where we're putting the output.
  output: {
    path: path.resolve(__dirname, isDocsBuild ? 'docs' : 'dist'),
    filename: 'ws-directives.js',
    library: 'wsAngularDirectives',
  },

  // We don't want to re-bundle peer dependencies with ws-directives; it's
  // up to the consumer of this library to include them in their app.
  externals: Object.keys(peerDependencies),

  plugins: [
    ...basePlugins,
    ...docsPlugins,
  ],

  // Output sourcemaps too, so people can debug their usage of this lib.
  devtool: 'sourcemap',

  // Transformations on various types of source files. When you import
  // something, it goes through these loaders prior to landing in the
  // bundle.
  module: {
    rules: loaders,
  },
};
