const webpack = require('webpack');
const path = require('path');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const OptimizeCssAssetsWebpackPlugin = require('optimize-css-assets-webpack-plugin');
const { peerDependencies } = require('./package.json');

const isDocsBuild = process.env.NODE_ENV === 'docs';
const isDevBuild = process.env.NODE_ENV === 'development';

const extraPlugins = isDocsBuild || isDevBuild ?
  [new HtmlWebpackPlugin({ template: 'index.html' })] :
  [];

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: [
    // Pull out CSS and put it in its own file. Otherwise it would be JSified
    // and included in the JS, which would make it harder to use by consumers
    // of this library.
    new ExtractTextPlugin('ws-directives.css'),

    // Don't output broken code; die instead.
    new webpack.NoEmitOnErrorsPlugin(),

    // Minify JS output.
    new webpack.optimize.UglifyJsPlugin({ sourceMap: true }),

    // Minify CSS output.
    new OptimizeCssAssetsWebpackPlugin(),
  ].concat(extraPlugins),

  // 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: {
    loaders: [
      // Lint source code.
      {
        enforce: 'pre',
        test: /\.js$/,
        exclude: /node_modules/,
        loader: 'eslint-loader',
      },
      // Allow ES6 in .js files.
      {
        test: /\.js$/,
        loader: 'babel-loader',
        exclude: /node_modules\/(?!(autonumeric)\/).*/,
      },
      // Lets you pull templates into the JS bundle by
      // simply importing them into your JS files.
      {
        test: /\.html$/,
        loader: 'html-loader',
      },
      // Lets you pull SCSS into the CSS bundle by
      // simply importing into your JS files. SCSS
      // will be transformed to CSS and autoprefixed
      // for you.
      {
        test: /\.scss$/,
        use: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: ['css-loader', 'sass-loader'],
        }),
      },
    ],
  },
};
