<commit_before>/*
 * Copyright (c) 2016-2019 Martin Donath <martin.donath@squidfunk.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

const fs = require("fs")
const cssmin = require("cssmin")
const path = require("path")
const html = require("html-minifier")
const uglify = require("uglify-js")
const webpack = require("webpack")

/* ----------------------------------------------------------------------------
 * Plugins
 * ------------------------------------------------------------------------- */

const CopyPlugin = require("copy-webpack-plugin")
const EventHooksPlugin = require("event-hooks-webpack-plugin")
const { CallbackTask } = require("event-hooks-webpack-plugin/lib/tasks")
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin")
const UglifyJsPlugin = require("uglifyjs-3-webpack-plugin")
const ImageminPlugin = require("imagemin-webpack-plugin").default
const ManifestPlugin = require("webpack-manifest-plugin")

/* ----------------------------------------------------------------------------
 * Configuration
 * ------------------------------------------------------------------------- */

module.exports = (_env, args) => { // eslint-disable-line complexity
  const config = {
    mode: args.mode,

    /* Entrypoints */
    entry: {

      /* Custom Modernizr build */
      "assets/javascripts/modernizr": path.resolve(
        __dirname, "src/assets/javascripts/modernizr.js"
      ),

      /* Application */
      "assets/javascripts/application": path.resolve(
        __dirname, "src/assets/javascripts/application.js"
      )
    },

    /* Loaders */
    module: {
      rules: [

        /* Babel ES6 transformations */
        {
          test: /\.jsx?$/,
          use: "babel-loader",
          exclude: /\/node_modules\//
        },

        /* Custom Modernizr build */
        {
          test: /\.modernizr-autorc$/,
          use: "modernizr-auto-loader"
        },

        /* SASS stylesheets */
        {
          test: /\.scss$/,
          use: [
            {
              loader: "file-loader",
              options: {
                name: `[name]${
                  args.mode === "production" ? ".[md5:hash:hex:8]" : ""
                }.css`,
                outputPath: "assets/stylesheets",
                publicPath: path.resolve(__dirname, "material")
              }
            },
            "extract-loader",
            {
              loader: "css-loader",
              options: {
                sourceMap: args.mode !== "production"
              }
            },
            {
              loader: "postcss-loader",
              options: {
                ident: "postcss",
                plugins: () => [
                  require("autoprefixer")(),
                  require("css-mqpacker")
                ],
                sourceMap: args.mode !== "production"
              }
            },
            {
              loader: "sass-loader",
              options: {
                includePaths: [
                  "node_modules/modularscale-sass/stylesheets",
                  "node_modules/material-design-color",
                  "node_modules/material-shadows"
                ],
                sourceMap: args.mode !== "production",
                sourceMapContents: true
              }
            }
          ]
        },

        /* Cache busting for SVGs */
        {
          test: /\.svg$/,
          use: `file-loader?name=[path][name]${
            args.mode === "production" ? ".[md5:hash:hex:8]" : ""
          }.[ext]&context=./src`
        }
      ]
    },

    /* Output */
    output: {
      path: path.resolve(__dirname, "material"),
      filename: `[name]${args.mode === "production" ? ".[chunkhash]" : ""}.js`,
      hashDigestLength: 8,
      libraryTarget: "window"
    },

    /* Plugins */
    plugins: [

      /* Provide JSX helper */
      new webpack.ProvidePlugin({
        JSX: path.resolve(__dirname, "src/assets/javascripts/providers/jsx.js")
      }),

      /* Copy and transform static assets */
      new CopyPlugin([

        /* Copy search language support files - we could define the languages
           package as entrypoints, but this leads to a lot of problems because
           the files have the structure lunr.[language].js, which some Webpack
           plugins will complain about. For this reason we only minify */
        {
          context: path.resolve(__dirname, "node_modules/lunr-languages"),
          to: "assets/javascripts/lunr",
          from: "*.js",
          transform: content => {
            return uglify.minify(content.toString()).code
          }
        },

        /* Copy web font files */
        {
          context: "src",
          from: "assets/fonts/**/*",
          ignore: "**/*.css"
        },

        /* Copy and minify web font stylesheets */
        {
          context: "src",
          from: "assets/fonts/*.css",
          transform: content => cssmin(content.toString())
        },

        /* Copy images without cache busting */
        {
          context: "src",
          from: "assets/images/*.{ico,png}"
        },

        /* Copy configuration */
        {
          context: "src",
          from: "**/*.{py,yml}"
        },

        /* Copy and minify HTML */
        {
          context: "src",
          from: "**/*.html",
          transform: content => {
            const metadata = require(path.resolve(__dirname, "package.json"))
            const banner =
              `{#-\n` +
              `  This file was automatically generated - do not edit\n` +
              `-#}\n`
            return banner + html.minify(content.toString(), {
              collapseBooleanAttributes: true,
              collapseWhitespace: true,
              collapseInlineTagWhitespace: false,
              conservativeCollapse: false,
              includeAutoGeneratedTags: false,
              minifyCSS: true,
              minifyJS: true,
              removeComments: true,
              removeScriptTypeAttributes: true,
              removeStyleLinkTypeAttributes: true
            })

              /* Remove empty lines without collapsing everything */
              .replace(/^\s*[\r\n]/gm, "")

              /* Write theme version into template */
              .replace("$md-name$", metadata.name)
              .replace("$md-version$", metadata.version)

              /* Write available search languages into template */
              .replace("$md-lunr-languages$",
                fs.readdirSync(
                  path.resolve(__dirname, "node_modules/lunr-languages")
                ).reduce((files, file) => {
                  const matches = file.match(/lunr.(\w{2}).js$/)
                  if (matches) {
                    const [, language] = matches
                    if (!["du", "jp"].includes(language))
                      files.push(`"${language}"`)
                  }
                  return files
                }, [])
                  .join(", "))
          }
        }
      ])
    ],

    /* Module resolver */
    resolve: {
      modules: [
        path.resolve(__dirname, "node_modules")
      ],
      extensions: [".js", ".jsx", ".scss"],
      alias: {
        modernizr$: path.resolve(__dirname, ".modernizr-autorc")
      }
    },

    /* Sourcemaps */
    devtool: args.mode !== "production" ? "inline-source-map" : "",

    /* Optimizations */
    optimization: {
      minimizer: [
        new UglifyJsPlugin(),
        new OptimizeCSSAssetsPlugin({})
      ],
      splitChunks: {
        cacheGroups: {
          commons: {
            chunks: "all",
            minChunks: 2,
            maxInitialRequests: 5,
            minSize: 0
          },
          modernizr: {
            test: "src/assets/javascripts/modernizr.js",
            chunks: "all",
            name: "modernizr",
            priority: 10,
            enforce: true
          }
        }
      }
    }
  }

  /* Production compilation */
  if (args.mode === "production") {
    config.plugins.push(

      /* Minify images */
      new ImageminPlugin({
        test: /\.(ico|png|svg)$/i,
        svgo: {
          plugins: [
            { cleanupIDs: false },
            { removeViewBox: false }
          ]
        }
      }),

      /* Write manifest */
      new ManifestPlugin({

        /* This is an ugly workaround for the fact that the manifest plugin
           doesn't handle multiple chunks. See http://bit.ly/2BbfER9 */
        map(file) {
          file.name = file.path.replace(/\.[a-z0-9].+\.(css|js|svg)/i, ".$1")
          return file
        }
      }),

      /* Apply manifest */
      new EventHooksPlugin({
        afterEmit: new CallbackTask((compilation, cb) => {
          const manifest = require(path.resolve("material/manifest.json"))
          Object.keys(compilation.assets).forEach(name => {
            if (name.match(/\.html/)) {
              const asset = compilation.assets[name]
              const replaced = Object.keys(manifest).reduce((source, key) => {
                return source.replace(key, manifest[key])
              }, asset.source())
              fs.writeFileSync(asset.existsAt, replaced)
            }
          })
          cb()
        })
      })
    )
  }

  /* Oh my god, that was a hell of a setup */
  return config
}
<commit_msg>Fixed linter errors<commit_after>/*
 * Copyright (c) 2016-2019 Martin Donath <martin.donath@squidfunk.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
 * IN THE SOFTWARE.
 */

const fs = require("fs")
const cssmin = require("cssmin")
const path = require("path")
const html = require("html-minifier")
const uglify = require("uglify-js")
const webpack = require("webpack")

/* ----------------------------------------------------------------------------
 * Plugins
 * ------------------------------------------------------------------------- */

const CopyPlugin = require("copy-webpack-plugin")
const EventHooksPlugin = require("event-hooks-webpack-plugin")
const { CallbackTask } = require("event-hooks-webpack-plugin/lib/tasks")
const OptimizeCSSAssetsPlugin = require("optimize-css-assets-webpack-plugin")
const UglifyJsPlugin = require("uglifyjs-3-webpack-plugin")
const ImageminPlugin = require("imagemin-webpack-plugin").default
const ManifestPlugin = require("webpack-manifest-plugin")

/* ----------------------------------------------------------------------------
 * Configuration
 * ------------------------------------------------------------------------- */

module.exports = (_env, args) => { // eslint-disable-line complexity
  const config = {
    mode: args.mode,

    /* Entrypoints */
    entry: {

      /* Custom Modernizr build */
      "assets/javascripts/modernizr": path.resolve(
        __dirname, "src/assets/javascripts/modernizr.js"
      ),

      /* Application */
      "assets/javascripts/application": path.resolve(
        __dirname, "src/assets/javascripts/application.js"
      )
    },

    /* Loaders */
    module: {
      rules: [

        /* Babel ES6 transformations */
        {
          test: /\.jsx?$/,
          use: "babel-loader",
          exclude: /\/node_modules\//
        },

        /* Custom Modernizr build */
        {
          test: /\.modernizr-autorc$/,
          use: "modernizr-auto-loader"
        },

        /* SASS stylesheets */
        {
          test: /\.scss$/,
          use: [
            {
              loader: "file-loader",
              options: {
                name: `[name]${
                  args.mode === "production" ? ".[md5:hash:hex:8]" : ""
                }.css`,
                outputPath: "assets/stylesheets",
                publicPath: path.resolve(__dirname, "material")
              }
            },
            "extract-loader",
            {
              loader: "css-loader",
              options: {
                sourceMap: args.mode !== "production"
              }
            },
            {
              loader: "postcss-loader",
              options: {
                ident: "postcss",
                plugins: () => [
                  require("autoprefixer")(),
                  require("css-mqpacker")
                ],
                sourceMap: args.mode !== "production"
              }
            },
            {
              loader: "sass-loader",
              options: {
                includePaths: [
                  "node_modules/modularscale-sass/stylesheets",
                  "node_modules/material-design-color",
                  "node_modules/material-shadows"
                ],
                sourceMap: args.mode !== "production",
                sourceMapContents: true
              }
            }
          ]
        },

        /* Cache busting for SVGs */
        {
          test: /\.svg$/,
          use: `file-loader?name=[path][name]${
            args.mode === "production" ? ".[md5:hash:hex:8]" : ""
          }.[ext]&context=./src`
        }
      ]
    },

    /* Output */
    output: {
      path: path.resolve(__dirname, "material"),
      filename: `[name]${args.mode === "production" ? ".[chunkhash]" : ""}.js`,
      hashDigestLength: 8,
      libraryTarget: "window"
    },

    /* Plugins */
    plugins: [

      /* Provide JSX helper */
      new webpack.ProvidePlugin({
        JSX: path.resolve(__dirname, "src/assets/javascripts/providers/jsx.js")
      }),

      /* Copy and transform static assets */
      new CopyPlugin([

        /* Copy search language support files - we could define the languages
           package as entrypoints, but this leads to a lot of problems because
           the files have the structure lunr.[language].js, which some Webpack
           plugins will complain about. For this reason we only minify */
        {
          context: path.resolve(__dirname, "node_modules/lunr-languages"),
          to: "assets/javascripts/lunr",
          from: "*.js",
          transform: content => {
            return uglify.minify(content.toString()).code
          }
        },

        /* Copy web font files */
        {
          context: "src",
          from: "assets/fonts/**/*",
          ignore: "**/*.css"
        },

        /* Copy and minify web font stylesheets */
        {
          context: "src",
          from: "assets/fonts/*.css",
          transform: content => cssmin(content.toString())
        },

        /* Copy images without cache busting */
        {
          context: "src",
          from: "assets/images/*.{ico,png}"
        },

        /* Copy configuration */
        {
          context: "src",
          from: "**/*.{py,yml}"
        },

        /* Copy and minify HTML */
        {
          context: "src",
          from: "**/*.html",
          transform: content => {
            const metadata = require(path.resolve(__dirname, "package.json"))
            const banner =
              "{#-\n" +
              "  This file was automatically generated - do not edit\n" +
              "-#}\n"
            return banner + html.minify(content.toString(), {
              collapseBooleanAttributes: true,
              collapseWhitespace: true,
              collapseInlineTagWhitespace: false,
              conservativeCollapse: false,
              includeAutoGeneratedTags: false,
              minifyCSS: true,
              minifyJS: true,
              removeComments: true,
              removeScriptTypeAttributes: true,
              removeStyleLinkTypeAttributes: true
            })

              /* Remove empty lines without collapsing everything */
              .replace(/^\s*[\r\n]/gm, "")

              /* Write theme version into template */
              .replace("$md-name$", metadata.name)
              .replace("$md-version$", metadata.version)

              /* Write available search languages into template */
              .replace("$md-lunr-languages$",
                fs.readdirSync(
                  path.resolve(__dirname, "node_modules/lunr-languages")
                ).reduce((files, file) => {
                  const matches = file.match(/lunr.(\w{2}).js$/)
                  if (matches) {
                    const [, language] = matches
                    if (!["du", "jp"].includes(language))
                      files.push(`"${language}"`)
                  }
                  return files
                }, [])
                  .join(", "))
          }
        }
      ])
    ],

    /* Module resolver */
    resolve: {
      modules: [
        path.resolve(__dirname, "node_modules")
      ],
      extensions: [".js", ".jsx", ".scss"],
      alias: {
        modernizr$: path.resolve(__dirname, ".modernizr-autorc")
      }
    },

    /* Sourcemaps */
    devtool: args.mode !== "production" ? "inline-source-map" : "",

    /* Optimizations */
    optimization: {
      minimizer: [
        new UglifyJsPlugin(),
        new OptimizeCSSAssetsPlugin({})
      ],
      splitChunks: {
        cacheGroups: {
          commons: {
            chunks: "all",
            minChunks: 2,
            maxInitialRequests: 5,
            minSize: 0
          },
          modernizr: {
            test: "src/assets/javascripts/modernizr.js",
            chunks: "all",
            name: "modernizr",
            priority: 10,
            enforce: true
          }
        }
      }
    }
  }

  /* Production compilation */
  if (args.mode === "production") {
    config.plugins.push(

      /* Minify images */
      new ImageminPlugin({
        test: /\.(ico|png|svg)$/i,
        svgo: {
          plugins: [
            { cleanupIDs: false },
            { removeViewBox: false }
          ]
        }
      }),

      /* Write manifest */
      new ManifestPlugin({

        /* This is an ugly workaround for the fact that the manifest plugin
           doesn't handle multiple chunks. See http://bit.ly/2BbfER9 */
        map(file) {
          file.name = file.path.replace(/\.[a-z0-9].+\.(css|js|svg)/i, ".$1")
          return file
        }
      }),

      /* Apply manifest */
      new EventHooksPlugin({
        afterEmit: new CallbackTask((compilation, cb) => {
          const manifest = require(path.resolve("material/manifest.json"))
          Object.keys(compilation.assets).forEach(name => {
            if (name.match(/\.html/)) {
              const asset = compilation.assets[name]
              const replaced = Object.keys(manifest).reduce((source, key) => {
                return source.replace(key, manifest[key])
              }, asset.source())
              fs.writeFileSync(asset.existsAt, replaced)
            }
          })
          cb()
        })
      })
    )
  }

  /* Oh my god, that was a hell of a setup */
  return config
}
<|endoftext|>


<commit_before>const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackTemplate = require('html-webpack-template');
const webpack = require('webpack');
const merge = require('webpack-merge');
const glob = require('glob');

const parts = require('./webpack.parts');

const PATHS = {
  app: path.join(__dirname, 'app'),
  build: path.join(__dirname, 'build'),
};

const common = merge([
  {
    // Entry accepts a path or an object of entries.
    // We'll be using the latter form given it's
    // convenient with more complex configurations.
    //
    // Entries have to resolve to files! It relies on Node.js
    // convention by default so if a directory contains *index.js*,
    // it will resolve to that.
    entry: {
      app: PATHS.app,
    },
    output: {
      path: PATHS.build,
      filename: '[name].js',
    },
    plugins: [
      new HtmlWebpackPlugin({
        template: HtmlWebpackTemplate,
        title: 'Webpack demo',
        appMountId: 'app', // Generate #app where to mount
        mobile: true, // Scale page on mobile
        inject: false, // html-webpack-template requires this to work
      }),
    ],
  },
  parts.lintCSS({
    include: PATHS.app,
    rules: {
      'color-hex-case': 'lower',
    },
  }),
  parts.loadImages({
    options: {
      limit: 15000,
    },
  }),
  parts.loadFonts(),
  parts.loadJavaScript({ include: PATHS.app }),
]);

module.exports = function(env) {
  process.env.BABEL_ENV = env;

  if (env === 'production') {
    return merge([
      common,
      {
        performance: {
          hints: 'warning', // 'error' or false are valid too
          maxEntrypointSize: 200000, // in bytes
          maxAssetSize: 200000, // in bytes
        },
        output: {
          chunkFilename: 'scripts/[chunkhash].js',
          filename: '[name].[chunkhash].js',
        },
        plugins: [
          new webpack.HashedModuleIdsPlugin(),
        ],
        recordsPath: 'records.json',
      },
      parts.setFreeVariable(
        'process.env.NODE_ENV',
        'production'
      ),
      parts.clean(PATHS.build),
      parts.minifyJavaScript({ useSourceMap: true }),
      parts.extractBundles({
        bundles: [
          {
            name: 'vendor',
            entries: ['react', 'react-dom'],
          },
          {
            name: 'manifest',
          },
        ],
      }),
      parts.generateSourceMaps({ type: 'source-map' }),
      parts.lintJavaScript({ include: PATHS.app }),
      parts.extractCSS({
        use: ['css-loader', parts.autoprefix()],
      }),
      parts.purifyCSS({
        paths: glob.sync(path.join(PATHS.app, '*')),
      }),
    ]);
  }

  return merge([
    common,
    {
      entry: {
        // react-hot-loader has to run before app!
        app: ['react-hot-loader/patch', PATHS.app],
      },
      plugins: [
        new webpack.NamedModulesPlugin(),
      ],
    },
    parts.generateSourceMaps({ type: 'cheap-module-eval-source-map' }),
    parts.loadCSS(),
    parts.devServer({
      // Customize host/port here if needed
      host: process.env.HOST,
      port: process.env.PORT,
    }),
    parts.lintJavaScript({
      include: PATHS.app,
      options: {
        // Emit warnings over errors to avoid crashing
        // HMR on error.
        emitWarning: true,
      },
    }),
  ]);
};
<commit_msg>Clear up sourcemap output<commit_after>const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const HtmlWebpackTemplate = require('html-webpack-template');
const webpack = require('webpack');
const merge = require('webpack-merge');
const glob = require('glob');

const parts = require('./webpack.parts');

const PATHS = {
  app: path.join(__dirname, 'app'),
  build: path.join(__dirname, 'build'),
};

const common = merge([
  {
    // Entry accepts a path or an object of entries.
    // We'll be using the latter form given it's
    // convenient with more complex configurations.
    //
    // Entries have to resolve to files! It relies on Node.js
    // convention by default so if a directory contains *index.js*,
    // it will resolve to that.
    entry: {
      app: PATHS.app,
    },
    output: {
      path: PATHS.build,
      filename: '[name].js',
    },
    plugins: [
      new HtmlWebpackPlugin({
        template: HtmlWebpackTemplate,
        title: 'Webpack demo',
        appMountId: 'app', // Generate #app where to mount
        mobile: true, // Scale page on mobile
        inject: false, // html-webpack-template requires this to work
      }),
    ],
  },
  parts.lintCSS({
    include: PATHS.app,
    rules: {
      'color-hex-case': 'lower',
    },
  }),
  parts.loadImages({
    options: {
      limit: 15000,
    },
  }),
  parts.loadFonts(),
  parts.loadJavaScript({ include: PATHS.app }),
]);

module.exports = function(env) {
  process.env.BABEL_ENV = env;

  if (env === 'production') {
    return merge([
      common,
      {
        performance: {
          hints: 'warning', // 'error' or false are valid too
          maxEntrypointSize: 200000, // in bytes
          maxAssetSize: 200000, // in bytes
        },
        output: {
          chunkFilename: 'scripts/[chunkhash].js',
          filename: '[name].[chunkhash].js',
        },
        plugins: [
          new webpack.HashedModuleIdsPlugin(),
        ],
        recordsPath: 'records.json',
      },
      parts.setFreeVariable(
        'process.env.NODE_ENV',
        'production'
      ),
      parts.clean(PATHS.build),
      parts.minifyJavaScript({ useSourceMap: true }),
      parts.extractBundles({
        bundles: [
          {
            name: 'vendor',
            entries: ['react', 'react-dom'],
          },
          {
            name: 'manifest',
          },
        ],
      }),
      parts.generateSourceMaps({ type: 'source-map' }),
      parts.lintJavaScript({ include: PATHS.app }),
      parts.extractCSS({
        use: ['css-loader', parts.autoprefix()],
      }),
      parts.purifyCSS({
        paths: glob.sync(path.join(PATHS.app, '*')),
      }),
    ]);
  }

  return merge([
    common,
    {
      entry: {
        // react-hot-loader has to run before app!
        app: ['react-hot-loader/patch', PATHS.app],
      },
      output: {
        devtoolModuleFilenameTemplate: 'webpack:///[absolute-resource-path]',
      },
      plugins: [
        new webpack.NamedModulesPlugin(),
      ],
    },
    parts.generateSourceMaps({ type: 'cheap-module-eval-source-map' }),
    parts.loadCSS(),
    parts.devServer({
      // Customize host/port here if needed
      host: process.env.HOST,
      port: process.env.PORT,
    }),
    parts.lintJavaScript({
      include: PATHS.app,
      options: {
        // Emit warnings over errors to avoid crashing
        // HMR on error.
        emitWarning: true,
      },
    }),
  ]);
};
<|endoftext|>


<commit_before>const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const OfflinePlugin = require('offline-plugin');

module.exports = {
  entry: [
    './index',
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[hash].bundle.js',
    chunkFilename: '[id].[hash].bundle.js',
    publicPath: '/',
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': `"${process.env.NODE_ENV}"`,
    }),
    new webpack.LoaderOptionsPlugin({
      options: {
        worker: {
          output: {
            filename: "[hash].worker.js",
            chunkFilename: "[id].[hash].worker.js"
          }
        }
      }
    }),
    new HtmlWebpackPlugin({
      title: 'Cleopatra',
      template: 'res/index.html',
      favicon: 'res/favicon.png',
    }),
  ],
  resolve: {
    alias: {
      'redux-devtools/lib': path.join(__dirname, '..', '..', 'src'),
      'redux-devtools': path.join(__dirname, '..', '..', 'src'),
      'react': path.join(__dirname, 'node_modules', 'react'),
    },
    extensions: ['.js'],
  },
  module: {
    rules: [{
      test: /\.js$/,
      loaders: ['babel-loader'],
      include: __dirname,
    }, {
      test: /\.json$/,
      loaders: ['json-loader'],
      include: __dirname,
    }, {
      test: /\.css?$/,
      loaders: ['style-loader', 'css-loader?minimize'],
      include: __dirname,
    }, {
      test: /\.jpg$/,
      loader: 'file-loader',
    }, {
      test: /\.png$/,
      loader: 'file-loader',
    }, {
      test: /\.svg$/,
      loader: 'file-loader',
    }],
  },
};

if (process.env.NODE_ENV === 'production') {
  module.exports.plugins.push(
    new OfflinePlugin({
      relativePaths: false,
      AppCache: false,
      ServiceWorker: {
        scope: '/',
        navigateFallbackURL: '/',
      },
    }));
} else if (process.env.NODE_ENV === 'development') {
  module.exports.devtool = 'source-map';
  module.exports.entry = ['webpack-dev-server/client?http://localhost:4242'].concat(module.exports.entry);
}
<commit_msg>Do the SPA fallback in the service worker cache lookup correctly.<commit_after>const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const OfflinePlugin = require('offline-plugin');

module.exports = {
  entry: [
    './index',
  ],
  output: {
    path: path.join(__dirname, 'dist'),
    filename: '[hash].bundle.js',
    chunkFilename: '[id].[hash].bundle.js',
    publicPath: '/',
  },
  plugins: [
    new webpack.DefinePlugin({
      'process.env.NODE_ENV': `"${process.env.NODE_ENV}"`,
    }),
    new webpack.LoaderOptionsPlugin({
      options: {
        worker: {
          output: {
            filename: "[hash].worker.js",
            chunkFilename: "[id].[hash].worker.js"
          }
        }
      }
    }),
    new HtmlWebpackPlugin({
      title: 'Cleopatra',
      template: 'res/index.html',
      favicon: 'res/favicon.png',
    }),
  ],
  resolve: {
    alias: {
      'redux-devtools/lib': path.join(__dirname, '..', '..', 'src'),
      'redux-devtools': path.join(__dirname, '..', '..', 'src'),
      'react': path.join(__dirname, 'node_modules', 'react'),
    },
    extensions: ['.js'],
  },
  module: {
    rules: [{
      test: /\.js$/,
      loaders: ['babel-loader'],
      include: __dirname,
    }, {
      test: /\.json$/,
      loaders: ['json-loader'],
      include: __dirname,
    }, {
      test: /\.css?$/,
      loaders: ['style-loader', 'css-loader?minimize'],
      include: __dirname,
    }, {
      test: /\.jpg$/,
      loader: 'file-loader',
    }, {
      test: /\.png$/,
      loader: 'file-loader',
    }, {
      test: /\.svg$/,
      loader: 'file-loader',
    }],
  },
};

if (process.env.NODE_ENV === 'production') {
  module.exports.plugins.push(
    new OfflinePlugin({
      relativePaths: false,
      AppCache: false,
      ServiceWorker: {
        scope: '/',
      },
      cacheMaps: [
        {
          requestTypes: null,
          match: function (url, request) {
            return url.origin === location.origin ? url.origin + '/' : null;
          },
        },
      ],
    }));
} else if (process.env.NODE_ENV === 'development') {
  module.exports.devtool = 'source-map';
  module.exports.entry = ['webpack-dev-server/client?http://localhost:4242'].concat(module.exports.entry);
}
<|endoftext|>


<commit_before>var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var path = require('path');
var env = process.env.NODE_ENV || 'production';

var eslintLoader = {
  test: /\.js$/,
  loaders: ['eslint'],
  include: [new RegExp(path.join(__dirname, 'src'))]
};

module.exports = {
  devtool: 'eval',

  entry: [
    './src/example/reset.css',
    './src/example/Example.js'
  ].concat(env === 'production' ? [] : [
      'webpack-dev-server/client?http://localhost:8080',
      'webpack/hot/only-dev-server'
    ]),

  output: {
    filename: 'index.js',
    path: path.resolve('./example')
  },

  plugins: [
    new HtmlWebpackPlugin(),
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"' + env + '"'
      }
    })
  ].concat(env === 'production' ? [] : [
      new webpack.HotModuleReplacementPlugin()
    ]),

  module: {
    loaders: [
      {test: /\.js$/, loaders: ['react-hot', 'babel'], include: [path.resolve('src')]},
      {
        test: /\.css$/,
        loader: 'style!css?modules&sourceMap&localIdentName=[name]__[local]___[hash:base64:5]'
      }
    ],
    preLoaders: env === 'production' ? [] : [
      eslintLoader
    ]
  },

  resolve: {
    extensions: ['', '.js']
  },

  stats: {
    colors: true
  },

  eslint: {
    configFile: 'src/.eslintrc'
  },

  devServer: {
    hot: true,
    historyApiFallback: true,
    stats: {
      // Do not show list of hundreds of files included in a bundle
      chunkModules: false,
      colors: true
    }
  }
};
<commit_msg>Simplify path resolution in webpack config<commit_after>var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
var path = require('path');
var env = process.env.NODE_ENV || 'production';

var eslintLoader = {
  test: /\.js$/,
  loaders: ['eslint'],
  include: path.resolve('src')
};

module.exports = {
  devtool: 'eval',

  entry: [
    './src/example/reset.css',
    './src/example/Example.js'
  ].concat(env === 'production' ? [] : [
      'webpack-dev-server/client?http://localhost:8080',
      'webpack/hot/only-dev-server'
    ]),

  output: {
    filename: 'index.js',
    path: path.resolve('./example')
  },

  plugins: [
    new HtmlWebpackPlugin(),
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: '"' + env + '"'
      }
    })
  ].concat(env === 'production' ? [] : [
      new webpack.HotModuleReplacementPlugin()
    ]),

  module: {
    loaders: [
      {test: /\.js$/, loaders: ['react-hot', 'babel'], include: [path.resolve('src')]},
      {
        test: /\.css$/,
        loader: 'style!css?modules&sourceMap&localIdentName=[name]__[local]___[hash:base64:5]'
      }
    ],
    preLoaders: env === 'production' ? [] : [
      eslintLoader
    ]
  },

  resolve: {
    extensions: ['', '.js']
  },

  stats: {
    colors: true
  },

  eslint: {
    configFile: 'src/.eslintrc'
  },

  devServer: {
    hot: true,
    historyApiFallback: true,
    stats: {
      // Do not show list of hundreds of files included in a bundle
      chunkModules: false,
      colors: true
    }
  }
};
<|endoftext|>


<commit_before>const webpack = require('webpack');

module.exports = {
  entry: {
    app: ['./src/_module.js', './src/validate.js', './src/orgnr.js', './src/personnummer.js']
  },
  resolve: {
    extensions: ['', '.js']
  },
  output: {
    path: './dist',
    filename: 'angular-input-types.min.js'
  },
  plugins: [
    new webpack.optimize.UglifyJsPlugin({
      minimize: true,
      compress: {
        drop_console: true
      },
      mangle: false
    }),
    new webpack.BannerPlugin(`Angular Input Types v0.1.0-SNAPSHOT
(c) 2017 Jon Wikman. https://github.com/FlaxHaxx/angular-input-types
License: MIT`)
  ]
};
<commit_msg>Using version from package.json in banner<commit_after>const webpack = require('webpack');

module.exports = {
  entry: {
    app: ['./src/_module.js', './src/validate.js', './src/orgnr.js', './src/personnummer.js']
  },
  resolve: {
    extensions: ['', '.js']
  },
  output: {
    path: './dist',
    filename: 'angular-input-types.min.js'
  },
  plugins: [
    new webpack.optimize.UglifyJsPlugin({
      minimize: true,
      compress: {
        drop_console: true
      },
      mangle: false
    }),
    new webpack.BannerPlugin('Angular Input Types v' + require('./package.json').version + `
(c) 2017 Jon Wikman. https://github.com/FlaxHaxx/angular-input-types
License: MIT`)
  ]
};
<|endoftext|>


<commit_before>var webpack = require('webpack');

module.exports = {
	entry: [
		'webpack-dev-server/client?http://localhost:8080',
		'webpack/hot/dev-server',
		'./src/sdk.ts'
	],
	output: {
		filename: 'SygicTravelSDK.js',
		path: __dirname + '/dist',
		library: 'SygicTravelSDK',
		libraryTarget: 'umd',
		umdNamedDefine: true
	},
	module: {
		rules: [
			{
				test: /\.ts$/,
				enforce: 'pre',
				loader: 'tslint-loader',
				options: {
					configFile: 'tslint.json',
					tsConfigFile: 'tsconfig.json'
				}
			},
			{
				test: /\.tsx?$/,
				loader: 'ts-loader',
				exclude: /node_modules/
			},
			{
				enforce: 'pre',
				test: /\.js$/,
				loader: "source-map-loader"
			},
			{
				enforce: 'pre',
				test: /\.tsx?$/,
				use: "source-map-loader"
			}
		]
	},
	resolve: {
		extensions: [".tsx", ".ts", ".js"]
	},
	devtool: 'inline-source-map',
	plugins: [
		new webpack.HotModuleReplacementPlugin(),
		new webpack.DefinePlugin({
			'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
		})
	],
	devServer: {
		hot: true,
		inline: false,
		contentBase: './build'
	}
};
<commit_msg>webpack: Loaders only for .ts<commit_after>var webpack = require('webpack');

module.exports = {
	entry: [
		'webpack-dev-server/client?http://localhost:8080',
		'webpack/hot/dev-server',
		'./src/sdk.ts'
	],
	output: {
		filename: 'SygicTravelSDK.js',
		path: __dirname + '/dist',
		library: 'SygicTravelSDK',
		libraryTarget: 'umd',
		umdNamedDefine: true
	},
	module: {
		rules: [
			{
				test: /\.ts$/,
				enforce: 'pre',
				loader: 'tslint-loader',
				options: {
					configFile: 'tslint.json',
					tsConfigFile: 'tsconfig.json'
				}
			},
			{
				test: /\.ts$/,
				loader: 'ts-loader',
				exclude: /node_modules/
			},
			{
				enforce: 'pre',
				test: /\.js$/,
				loader: "source-map-loader"
			},
			{
				enforce: 'pre',
				test: /\.ts$/,
				use: "source-map-loader"
			}
]
	},
	resolve: {
		extensions: [".tsx", ".ts", ".js"]
	},
	devtool: 'inline-source-map',
	plugins: [
		new webpack.HotModuleReplacementPlugin(),
		new webpack.DefinePlugin({
			'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
		})
	],
	devServer: {
		hot: true,
		inline: false,
		contentBase: './build'
	}
};
<|endoftext|>


<commit_before>const path = require('path');

const ExtractTextPlugin = require('extract-text-webpack-plugin');
const webpack = require('webpack');

module.exports = {
  entry: {
    vendor: './src/vendor.js',
    mb: './src/mb/index.jsx'
  },
  output: {
    filename: 'assets/js/[name].js',
    chunkFilename: 'assets/js/chunk.[id].js',
    path: path.resolve(__dirname, 'public'),
    publicPath: '/'
  },
  devServer: {
    contentBase: path.resolve(__dirname, 'public'),
  },
  resolve: {
    extensions: ['.js', '.jsx'],
    alias: {
      'normalize.css': path.resolve(__dirname, './node_modules/normalize.css/normalize.css')
    }
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        loader: 'babel-loader'
      },
      {
        test: /\.less$/,
        loader: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: ['css-loader', 'less-loader']
        })
      },
      {
        test: /\.html$/,
        loader: 'file-loader?name=[name].[ext]!extract-loader!html-loader'
      }
    ]
  },
  plugins: [
    new webpack.optimize.CommonsChunkPlugin({
      names: 'vendor'
    }),
    new ExtractTextPlugin('assets/css/[name].css')
  ]
};
<commit_msg>Add file-loader for image resources<commit_after>const path = require('path');

const ExtractTextPlugin = require('extract-text-webpack-plugin');
const webpack = require('webpack');

module.exports = {
  entry: {
    vendor: './src/vendor/index.js',
    mb: './src/mb/index.jsx'
  },
  output: {
    filename: 'assets/js/[name].js',
    chunkFilename: 'assets/js/chunk.[id].js',
    path: path.resolve(__dirname, 'public'),
    publicPath: '/'
  },
  devServer: {
    contentBase: path.resolve(__dirname, 'public'),
  },
  resolve: {
    extensions: ['.js', '.jsx'],
    alias: {
      'normalize.css': path.resolve(__dirname, './node_modules/normalize.css/normalize.css')
    }
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        loader: 'babel-loader'
      },
      {
        test: /\.less$/,
        loader: ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: ['css-loader', 'less-loader']
        })
      },
      {
        test: /\.jpg$/,
        loader: 'url-loader?limit=10240'
      },
      {
        test: /\.png$/,
        loader: 'url-loader?limit=10240'
      },
      {
        test: /\.html$/,
        use: [
          'file-loader?name=[name].html',
          'extract-loader',
          'html-loader'
        ]
      }
    ]
  },
  plugins: [
    new webpack.optimize.CommonsChunkPlugin({
      names: 'vendor'
    }),
    new ExtractTextPlugin('assets/css/[name].css')
  ]
};
<|endoftext|>


<commit_before>var path = require('path');
var webpack = require('webpack')

module.exports = {
    entry: {
        index: [
            './index.js'
        ]
    },
    output: {
        path: path.join(__dirname, 'build'),
        publicPath: '/',
        filename: '[name].js',
        library: 'react-sparklines',
        libraryTarget: 'commonjs2'
    },
    externals: { react: 'react' },
    module: {
        loaders: [{
            test: /\.jsx?$/,
            exclude: /(node_modules)/,
            loader: 'babel'
        }]
    },
    resolve: {
        extensions: ['', '.js', '.jsx']
    }
};
<commit_msg>Switch build type to UMD to support use in projects not using npm for package management.<commit_after>var path = require('path');
var webpack = require('webpack')

module.exports = {
    entry: {
        index: [
            './index.js'
        ]
    },
    output: {
        path: path.join(__dirname, 'build'),
        publicPath: '/',
        filename: '[name].js',
        library: 'ReactSparklines',
        libraryTarget: 'umd'
    },
    externals: {
        react: {
            root: 'React',
            commonjs2: 'react',
            commonjs: 'react',
            amd: 'react'
        }
    },
    externals: { react: 'react' },
    module: {
        loaders: [{
            test: /\.jsx?$/,
            exclude: /(node_modules)/,
            loader: 'babel'
        }]
    },
    resolve: {
        extensions: ['', '.js', '.jsx']
    }
};
<|endoftext|>


<commit_before>/* global __dirname */

var child_process = require('child_process'); // eslint-disable-line camelcase
var process = require('process');

var minimize
    = process.argv.indexOf('-p') !== -1
        || process.argv.indexOf('--optimize-minimize') !== -1;

module.exports = {
    devtool: 'source-map',
    entry: {
        'lib-jitsi-meet': './JitsiMeetJS.js'
    },
    module: {
        loaders: [ {
            // Version this build of the lib-jitsi-meet library.

            loader: 'string-replace',
            query: {
                flags: 'g',
                replace:
                    child_process.execSync( // eslint-disable-line camelcase
                            __dirname + '/get-version.sh')

                        // The type of the return value of
                        // child_process.execSync is either Buffer or String.
                        .toString()

                            // Shells may automatically append CR and/or LF
                            // characters to the output.
                            .trim(),
                search: '{#COMMIT_HASH#}'
            },
            test: __dirname + '/JitsiMeetJS.js'
        }, {
            // Transpile ES2015 (aka ES6) to ES5.

            exclude: [
                __dirname + '/modules/RTC/adapter.screenshare.js',
                __dirname + '/node_modules/'
            ],
            loader: 'babel',
            query: {
                presets: [
                    'es2015'
                ]
            },
            test: /\.js$/
        } ]
    },
    node: {
        // Allow the use of the real filename of the module being executed. By
        // default Webpack does not leak path-related information and provides a
        // value that is a mock (/index.js).
        __filename: true
    },
    output: {
        filename: '[name]' + (minimize ? '.min' : '') + '.js',
        library: 'JitsiMeetJS',
        libraryTarget: 'umd',
        sourceMapFilename: '[name].' + (minimize ? 'min' : 'js') + '.map'
    }
};
<commit_msg>Prepare for webpack 2<commit_after>/* global __dirname */

var child_process = require('child_process'); // eslint-disable-line camelcase
var process = require('process');
var webpack = require('webpack');

var minimize
    = process.argv.indexOf('-p') !== -1
        || process.argv.indexOf('--optimize-minimize') !== -1;
var plugins = [];

if (minimize) {
    // While webpack will automatically insert UglifyJsPlugin when minimize is
    // true, the defaults of UglifyJsPlugin in webpack 1 and webpack 2 are
    // different. Explicitly state what we want even if we want defaults in
    // order to prepare for webpack 2.
    plugins.push(new webpack.optimize.UglifyJsPlugin({
        compress: {
            // It is nice to see warnings from UglifyJsPlugin that something is
            // unused and, consequently, is removed. The default is false in
            // webpack 2.
            warnings: true
        },

        // Use the source map to map error message locations to modules. The
        // default is false in webpack 2.
        sourceMap: true
    }));
}

module.exports = {
    devtool: 'source-map',
    entry: {
        'lib-jitsi-meet': './JitsiMeetJS.js'
    },
    module: {
        loaders: [ {
            // Version this build of the lib-jitsi-meet library.

            loader: 'string-replace-loader',
            query: {
                flags: 'g',
                replace:
                    child_process.execSync( // eslint-disable-line camelcase
                            __dirname + '/get-version.sh')

                        // The type of the return value of
                        // child_process.execSync is either Buffer or String.
                        .toString()

                            // Shells may automatically append CR and/or LF
                            // characters to the output.
                            .trim(),
                search: '{#COMMIT_HASH#}'
            },
            test: __dirname + '/JitsiMeetJS.js'
        }, {
            // Transpile ES2015 (aka ES6) to ES5.

            exclude: [
                __dirname + '/modules/RTC/adapter.screenshare.js',
                __dirname + '/node_modules/'
            ],
            loader: 'babel-loader',
            query: {
                presets: [
                    'es2015'
                ]
            },
            test: /\.js$/
        } ]
    },
    node: {
        // Allow the use of the real filename of the module being executed. By
        // default Webpack does not leak path-related information and provides a
        // value that is a mock (/index.js).
        __filename: true
    },
    output: {
        filename: '[name]' + (minimize ? '.min' : '') + '.js',
        library: 'JitsiMeetJS',
        libraryTarget: 'umd',
        sourceMapFilename: '[name].' + (minimize ? 'min' : 'js') + '.map'
    },
    plugins: plugins
};
<|endoftext|>


<commit_before>const {
  DefinePlugin,
  HotModuleReplacementPlugin,
  NoErrorsPlugin,
  optimize,
} = require('webpack');
const { OccurenceOrderPlugin, UglifyJsPlugin } = optimize;
const path = require('path');
const autoprefixer = require('autoprefixer');
const env = process.env.NODE_ENV || 'development';
const isDev = env === 'development';

const defineConstPlugin = new DefinePlugin({
  __DEV__: isDev,
});

module.exports = {
  devtool: isDev ? 'cheap-module-eval-source-map' : 'source-map',

  entry: isDev ? [
    'babel-polyfill',
    'webpack-hot-middleware/client',
    './src/index',
  ] : [
    'babel-polyfill',
    './src/index',
  ],

  output: {
    path: path.join(__dirname, 'dist', 'static'),
    filename: 'bundle.js',
    publicPath: '/static/',
  },

  plugins: isDev ? [
    defineConstPlugin,
    new HotModuleReplacementPlugin(),
    new NoErrorsPlugin(),
  ] : [
    defineConstPlugin,
    new OccurenceOrderPlugin(),
    new UglifyJsPlugin({
      compressor: { warnings: false },
    }),
  ],

  module: {
    loaders: [{
      test: /\.js$/,
      loaders: [ 'babel' ],
      include: path.join(__dirname, 'src'),
    }, {
      test: /\.css$/,
      loaders: [
        'style-loader',
        'css-loader?modules&localIdentName=[name]__[local]__[hash:base64:5]',
        'postcss-loader',
      ],
    }, {
      test: /\.(png|jpg)$/,
      loader: 'url-loader?limit=8192',
    }],
  },

  postcss: [
    autoprefixer({ browsers: [ 'last 2 versions' ] }),
  ],
};
<commit_msg>destructuring in webpack.config.js broke the build<commit_after>const webpack = require('webpack');
const path = require('path');
const autoprefixer = require('autoprefixer');
const env = process.env.NODE_ENV || 'development';
const isDev = env === 'development';

const defineConstPlugin = new webpack.DefinePlugin({
  __DEV__: isDev,
});

module.exports = {
  devtool: isDev ? 'cheap-module-eval-source-map' : 'source-map',

  entry: isDev ? [
    'babel-polyfill',
    'webpack-hot-middleware/client',
    './src/index',
  ] : [
    'babel-polyfill',
    './src/index',
  ],

  output: {
    path: path.join(__dirname, 'dist', 'static'),
    filename: 'bundle.js',
    publicPath: '/static/',
  },

  plugins: isDev ? [
    defineConstPlugin,
    new webpack.HotModuleReplacementPlugin(),
    new webpack.NoErrorsPlugin(),
  ] : [
    defineConstPlugin,
    new webpack.optimize.OccurenceOrderPlugin(),
    new webpack.optimize.UglifyJsPlugin({
      compressor: { warnings: false },
    }),
  ],

  module: {
    loaders: [{
      test: /\.js$/,
      loaders: [ 'babel' ],
      include: path.join(__dirname, 'src'),
    }, {
      test: /\.css$/,
      loaders: [
        'style-loader',
        'css-loader?modules&localIdentName=[name]__[local]__[hash:base64:5]',
        'postcss-loader',
      ],
    }, {
      test: /\.(png|jpg)$/,
      loader: 'url-loader?limit=8192',
    }],
  },

  postcss: [
    autoprefixer({ browsers: [ 'last 2 versions' ] }),
  ],
};
<|endoftext|>


<commit_before>var path = require('path')
var webpack = require('webpack')

module.exports = {
  devtool: 'cheap-module-eval-source-map',
  // entry: [
  //   // 'webpack-hot-middleware/client',
  //   './app/index.es6'
  // ],
  // output: {
  //   path: path.join(__dirname, 'dist'),
  //   filename: 'bundle.js',
  //   publicPath: '/static/'
  // },
  // devServer: {
  //   // contentBase: './public',
  //   historyApiFallback: true
  // },

  entry: [
    'webpack-dev-server/client?http://localhost:8080',
    'webpack/hot/only-dev-server',
    `./app/index.es6`
  ],
  output: {
    path: path.resolve(__dirname, 'public'),
    publicPath: '/',
    filename: 'bundle.js'
  },
  // resolve: {
  //   modulesDirectories: [cwd, 'node_modules'],
  //   extensions: ['', '.js', '.jsx', '.json']
  // },
  devServer: {
    contentBase: './public',
    hot: true,
    historyApiFallback: true,
  },

  plugins: [
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin()
  ],
  module: {
    loaders: [
      {
        test: /\.es6$/,
        exclude: /node_modules/,
        loader: 'react-hot!babel',
        include: __dirname
      },
      {
        test: /\.scss$/,
        exclude: /node_modules/,
        loaders: ['style', 'css', 'sass']
      },
      // {
      //   test: /\.svg$/,
      //   loader: 'file',
      //   include: PATHS.assets
      // },
      {
        test: /\.css$/,
        exclude: /node_modules/,
        loader: 'style!css'
      },
      // {
      //   test: [/fontawesome-webfont\.svg/, /fontawesome-webfont\.eot/, /fontawesome-webfont\.ttf/, /fontawesome-webfont\.woff/, /fontawesome-webfont\.woff2/],
      //   loader: 'file?name=fonts/[name].[ext]',
      //   include: /node_modules/
      // }
    ]
  }
}

// const PATHS = {
//   app: path.join(__dirname, 'app'),
//   public: path.resolve(__dirname, 'public'),
//   assets: path.join(__dirname, 'app/assets')
// };

// const config = {
//   entry: {
//     app: './app/js/app.bundle.es6'
//   },
//   output: {
//     path: PATHS.public,
//     publicPath: '/',
//     filename: 'bundle.js'
//   },
//   devServer: {
//     contentBase: './public',
//     historyApiFallback: true
//   },
//   devtool: 'eval-source-map',
//   noInfo: true,
//   module: {
//     loaders: [
//       {
//         test: /\.es6?$/,
//         exclude: /node_modules/,
//         loader: 'babel'
//       },
//       {
//         test: /\.scss$/,
//         loaders: ['style', 'css', 'sass']
//       },
//       {
//         test: /\.svg$/,
//         loader: 'file',
//         include: PATHS.assets
//       },
//       {
//         test: /\.css$/,
//         loader: 'style!css'
//       },
//       {
//         test: /\.html$/,
//         loader: 'ngtemplate?relativeTo=' + PATHS.app + '/!html'
//       },
//       {
//         test: [/fontawesome-webfont\.svg/, /fontawesome-webfont\.eot/, /fontawesome-webfont\.ttf/, /fontawesome-webfont\.woff/, /fontawesome-webfont\.woff2/],
//         loader: 'file?name=fonts/[name].[ext]',
//         include: /node_modules/
//       }
//     ]
//   },
//   plugins: [
//     new webpack.ProvidePlugin({
//       $: 'jquery',
//       jQuery: 'jquery'
//     })
//   ]
// };

// module.exports = config;<commit_msg>- cleanup webpack config<commit_after>var path = require('path')
var webpack = require('webpack')

module.exports = {
  devtool: 'cheap-module-eval-source-map',
  entry: [
    'webpack-dev-server/client?http://localhost:8080',
    'webpack/hot/only-dev-server',
    `./app/index.es6`
  ],
  output: {
    path: path.resolve(__dirname, 'public'),
    publicPath: '/',
    filename: 'bundle.js'
  },
  devServer: {
    contentBase: './public',
    hot: true,
    historyApiFallback: true,
  },

  plugins: [
    new webpack.optimize.OccurrenceOrderPlugin(),
    new webpack.HotModuleReplacementPlugin()
  ],
  module: {
    loaders: [
      {
        test: /\.es6$/,
        exclude: /node_modules/,
        loader: 'react-hot!babel',
        include: __dirname
      },
      {
        test: /\.scss$/,
        exclude: /node_modules/,
        loaders: ['style', 'css', 'sass']
      },
      {
        test: /\.css$/,
        exclude: /node_modules/,
        loader: 'style!css'
      }
    ]
  }
};<|endoftext|>


<commit_before>const path = require('path');
const dotenv = require('dotenv');
dotenv.config({path: '.env'});
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const { AureliaPlugin, ModuleDependenciesPlugin } = require('aurelia-webpack-plugin');
const { optimize: { CommonsChunkPlugin }, ProvidePlugin } = require('webpack');
const webpack = require('webpack');
// config helpers:
const ensureArray = (config) => config && (Array.isArray(config) ? config : [config]) || [];
const when = (condition, config, negativeConfig) =>
condition ? ensureArray(config) : ensureArray(negativeConfig);
// primary config:
const title = 'Web Jam LLC';
const outDir = path.resolve(__dirname, 'dist');
const srcDir = path.resolve(__dirname, 'src');
const nodeModulesDir = path.resolve(__dirname, 'node_modules');
const baseUrl = '/';
const cssRules = [
  { loader: 'css-loader' },
  {
    loader: 'postcss-loader',
    options: { plugins: () => [require('autoprefixer')({ browsers: ['last 2 versions'] })]}
  }
];

module.exports = ({production, server, extractCss, coverage} = {}) => ({
  resolve: {
    extensions: ['.js'],
    modules: [srcDir, 'node_modules']
  },
  devtool: production ? 'source-map' : 'cheap-module-eval-source-map',
  entry: {
    app: ['aurelia-bootstrapper'],
    vendor: ['bluebird', 'jquery', 'bootstrap', 'whatwg-fetch', 'isomorphic-fetch']
  },
  output: {
    path: outDir,
    publicPath: baseUrl,
    filename: production ? '[name].[chunkhash].bundle.js' : '[name].[hash].bundle.js',
    sourceMapFilename: production ? '[name].[chunkhash].bundle.map' : '[name].[hash].bundle.map',
    chunkFilename: production ? '[name].[chunkhash].chunk.js' : '[name].[hash].chunk.js'
  },
  devServer: {
    contentBase: outDir,
    historyApiFallback: true,
    port: parseInt(process.env.PORT, 10)
  },
  module: {
    rules: [
      // CSS required in JS/TS files should use the style-loader that auto-injects it into the website
      // only when the issuer is a .js/.ts file, so the loaders are not applied inside html templates
      {
        test: /\.css$/i,
        issuer: [{ not: [{ test: /\.html$/i }] }],
        use: extractCss ? ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: cssRules
        }) : ['style-loader', ...cssRules]
      },
      {
        test: /\.css$/i,
        issuer: [{ test: /\.html$/i }],
        // CSS required in templates cannot be extracted safely
        // because Aurelia would try to require it again in runtime
        use: cssRules
      },
      { test: /\.html$/i, loader: 'html-loader' },
      { test: /\.js$/i, loader: 'babel-loader', exclude: nodeModulesDir,
        options: coverage ? { sourceMap: 'inline', plugins: [ 'istanbul' ] } : {}
      },
    { test: /\.json$/i, loader: 'json-loader' },
    // use Bluebird as the global Promise implementation:
    { test: /[\/\\]node_modules[\/\\]bluebird[\/\\].+\.js$/, loader: 'expose-loader?Promise' },
    // exposes jQuery globally as $ and as jQuery:
    { test: require.resolve('jquery'), loader: 'expose-loader?$!expose-loader?jQuery' },
    // embed small images and fonts as Data Urls and larger ones as files:
    { test: /\.(png|gif|jpg|cur)$/i, loader: 'url-loader', options: { limit: 8192 } },
    { test: /\.woff2(\?v=[0-9]\.[0-9]\.[0-9])?$/i, loader: 'url-loader', options: { limit: 10000, mimetype: 'application/font-woff2' } },
    { test: /\.woff(\?v=[0-9]\.[0-9]\.[0-9])?$/i, loader: 'url-loader', options: { limit: 10000, mimetype: 'application/font-woff' } },
    // load these fonts normally, as files:
    { test: /\.(ttf|eot|svg|otf)(\?v=[0-9]\.[0-9]\.[0-9])?$/i, loader: 'file-loader' }
    ]
  },
  plugins: [
    new AureliaPlugin(),
    new ModuleDependenciesPlugin({
      'aurelia-auth': ['./auth-filter'],
      'aurelia-config': ['./aurelia-config'],
      'au-table': ['./au-table', './au-table-select', './au-table-sort', './au-table-pagination'],
      'aurelia-validation': [
        './aurelia-validation',
        './controller-validate-result',
        './get-target-dom-element',
        './property-info',
        './validate-binding-behavior-base',
        './validate-binding-behavior',
        './validate-instruction',
        './validate-result',
        './validate-trigger',
        './validation-controller-factory',
        './validation-controller',
        './validation-errors-custom-attribute',
        './validation-renderer-custom-attribute',
        './validation-renderer',
        './validator'
      ]
    }),
    new ProvidePlugin({
      'Promise': 'bluebird',
      '$': 'jquery',
      'jQuery': 'jquery',
      'window.jQuery': 'jquery',
      Popper: ['popper.js', 'default'] // Bootstrap 4 Dependency.
    }),
    new HtmlWebpackPlugin({
      template: 'index.ejs',
      minify: production ? {
        removeComments: true,
        collapseWhitespace: true
      } : undefined,
      metadata: {
      // available in index.ejs //
        title, server, baseUrl
      }
    }),
    new CopyWebpackPlugin(
      [{ from: 'static/favicon.ico', to: 'favicon.ico' },
    { from: 'static/imgs', to: 'static/imgs' }]
  ),
    new webpack.EnvironmentPlugin(['NODE_ENV', 'AuthProductionBaseURL', 'PORT', 'BackendUrl', 'GoogleClientId', 'userRoles']),
    new webpack.DefinePlugin({'process.env': Object.keys(process.env).reduce((o, k) => {
      o[k] = JSON.stringify(process.env[k]);
      return o;
    }, {})}
),
    new CopyWebpackPlugin([
  { from: 'static/music/DG.mp3', to: 'DG.mp3' },
  { from: 'static/music/MRM.mp3', to: 'MRM.mp3' },
  { from: 'static/music/AT.mp3', to: 'AT.mp3' },
  { from: 'static/music/TTGA.mp3', to: 'TTGA.mp3' },
  { from: 'static/WebJamLLC_FactSheet.pdf', to: 'WebJamLLC_FactSheet.pdf' }
    ]),
    ...when(extractCss, new ExtractTextPlugin({
      filename: production ? '[contenthash].css' : '[id].css',
      allChunks: true
    })),
    ...when(production, new CommonsChunkPlugin({
      name: ['common']
    })),
    ...when(production, new CopyWebpackPlugin([
  { from: 'static/favicon.ico', to: 'favicon.ico' }
    ]))
  ]
});
<commit_msg>webpack configuration for webpack 4<commit_after>const path = require('path');
const dotenv = require('dotenv');
dotenv.config({path: '.env'});
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const { AureliaPlugin, ModuleDependenciesPlugin } = require('aurelia-webpack-plugin');
const { ProvidePlugin } = require('webpack');
const webpack = require('webpack');
// config helpers:
const ensureArray = (config) => config && (Array.isArray(config) ? config : [config]) || [];
const when = (condition, config, negativeConfig) =>
condition ? ensureArray(config) : ensureArray(negativeConfig);
// primary config:
const title = 'Web Jam LLC';
const outDir = path.resolve(__dirname, 'dist');
const srcDir = path.resolve(__dirname, 'src');
const nodeModulesDir = path.resolve(__dirname, 'node_modules');
const baseUrl = '/';
const cssRules = [
  { loader: 'css-loader' },
  {
    loader: 'postcss-loader',
    options: { plugins: () => [require('autoprefixer')({ browsers: ['last 2 versions'] })]}
  }
];

module.exports = ({production, server, extractCss, coverage} = {}) => ({
  resolve: {
    extensions: ['.js'],
    modules: [srcDir, 'node_modules']
  },
  devtool: production ? 'source-map' : 'cheap-module-eval-source-map',
  entry: {
    app: ['aurelia-bootstrapper'],
    vendor: ['bluebird', 'jquery', 'bootstrap', 'whatwg-fetch', 'isomorphic-fetch']
  },
  output: {
    path: outDir,
    publicPath: baseUrl,
    filename: production ? '[name].[chunkhash].bundle.js' : '[name].[hash].bundle.js',
    sourceMapFilename: production ? '[name].[chunkhash].bundle.map' : '[name].[hash].bundle.map',
    chunkFilename: production ? '[name].[chunkhash].chunk.js' : '[name].[hash].chunk.js'
  },
  devServer: {
    contentBase: outDir,
    historyApiFallback: true,
    port: parseInt(process.env.PORT, 10)
  },
  module: {
    rules: [
      // CSS required in JS/TS files should use the style-loader that auto-injects it into the website
      // only when the issuer is a .js/.ts file, so the loaders are not applied inside html templates
      {
        test: /\.css$/i,
        issuer: [{ not: [{ test: /\.html$/i }] }],
        use: extractCss ? ExtractTextPlugin.extract({
          fallback: 'style-loader',
          use: cssRules
        }) : ['style-loader', ...cssRules]
      },
      {
        test: /\.css$/i,
        issuer: [{ test: /\.html$/i }],
        // CSS required in templates cannot be extracted safely
        // because Aurelia would try to require it again in runtime
        use: cssRules
      },
      { test: /\.html$/i, loader: 'html-loader' },
      { test: /\.js$/i, loader: 'babel-loader', exclude: nodeModulesDir,
        options: coverage ? { sourceMap: 'inline', plugins: [ 'istanbul' ] } : {}
      },
    { test: /\.json$/i, loader: 'json-loader' },
    // use Bluebird as the global Promise implementation:
    { test: /[\/\\]node_modules[\/\\]bluebird[\/\\].+\.js$/, loader: 'expose-loader?Promise' },
    // exposes jQuery globally as $ and as jQuery:
    { test: require.resolve('jquery'), loader: 'expose-loader?$!expose-loader?jQuery' },
    // embed small images and fonts as Data Urls and larger ones as files:
    { test: /\.(png|gif|jpg|cur)$/i, loader: 'url-loader', options: { limit: 8192 } },
    { test: /\.woff2(\?v=[0-9]\.[0-9]\.[0-9])?$/i, loader: 'url-loader', options: { limit: 10000, mimetype: 'application/font-woff2' } },
    { test: /\.woff(\?v=[0-9]\.[0-9]\.[0-9])?$/i, loader: 'url-loader', options: { limit: 10000, mimetype: 'application/font-woff' } },
    // load these fonts normally, as files:
    { test: /\.(ttf|eot|svg|otf)(\?v=[0-9]\.[0-9]\.[0-9])?$/i, loader: 'file-loader' }
    ]
  },
  optimization: {
    minimize: false
  },
  plugins: [
    new AureliaPlugin(),
    new ModuleDependenciesPlugin({
      'aurelia-auth': ['./auth-filter'],
      'aurelia-config': ['./aurelia-config'],
      'au-table': ['./au-table', './au-table-select', './au-table-sort', './au-table-pagination'],
      'aurelia-validation': [
        './aurelia-validation',
        './controller-validate-result',
        './get-target-dom-element',
        './property-info',
        './validate-binding-behavior-base',
        './validate-binding-behavior',
        './validate-instruction',
        './validate-result',
        './validate-trigger',
        './validation-controller-factory',
        './validation-controller',
        './validation-errors-custom-attribute',
        './validation-renderer-custom-attribute',
        './validation-renderer',
        './validator'
      ]
    }),
    new ProvidePlugin({
      'Promise': 'bluebird',
      '$': 'jquery',
      'jQuery': 'jquery',
      'window.jQuery': 'jquery',
      Popper: ['popper.js', 'default'] // Bootstrap 4 Dependency.
    }),
    new HtmlWebpackPlugin({
      template: 'index.ejs',
      minify: production ? {
        removeComments: true,
        collapseWhitespace: true
      } : undefined,
      metadata: {
      // available in index.ejs //
        title, server, baseUrl
      }
    }),
    new CopyWebpackPlugin(
      [{ from: 'static/favicon.ico', to: 'favicon.ico' },
    { from: 'static/imgs', to: 'static/imgs' }]
  ),
    new webpack.EnvironmentPlugin(['NODE_ENV', 'AuthProductionBaseURL', 'PORT', 'BackendUrl', 'GoogleClientId', 'userRoles']),
    new webpack.DefinePlugin({'process.env': Object.keys(process.env).reduce((o, k) => {
      o[k] = JSON.stringify(process.env[k]);
      return o;
    }, {})}
),
    new CopyWebpackPlugin([
  { from: 'static/music/DG.mp3', to: 'DG.mp3' },
  { from: 'static/music/MRM.mp3', to: 'MRM.mp3' },
  { from: 'static/music/AT.mp3', to: 'AT.mp3' },
  { from: 'static/music/TTGA.mp3', to: 'TTGA.mp3' },
  { from: 'static/WebJamLLC_FactSheet.pdf', to: 'WebJamLLC_FactSheet.pdf' }
    ]),
    ...when(extractCss, new ExtractTextPlugin({
      filename: production ? '[contenthash].css' : '[id].css',
      allChunks: true
    })),
    ...when(production, new CopyWebpackPlugin([
  { from: 'static/favicon.ico', to: 'favicon.ico' }
    ]))
  ]
});
<|endoftext|>


<commit_before>'use strict'

const CleanWebpackPlugin = require('clean-webpack-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const path = require('path')
const R = require('ramda')
const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin')
const UglifyJSPlugin = require('uglifyjs-webpack-plugin')
const webpack = require('webpack')
const ZipPlugin = require('zip-webpack-plugin')
const {BundleAnalyzerPlugin} = require('webpack-bundle-analyzer')

const pkg = require('./package')
const {
  appNames, commonChunkName, outputDir, sourceDir
} = require('./config')

const getMergedConfigByEnv = R.converge(R.mergeDeepWith(R.concat), [
  R.prop('default'),
  R.propOr({}, process.env.NODE_ENV)
])

const cssLoaderOptions = {
  modules: true,
  importLoaders: 1,
  localIdentName: '[path]___[name]__[local]___[hash:base64:5]'
}

const webpackConfig = getMergedConfigByEnv({
  default: {
    entry: R.converge(R.zipObj, [R.identity, R.map(R.concat(`./${sourceDir}/js/`))])(appNames),
    module: {
      rules: [
        {
          test: /\.jsx?$/,
          exclude: /node_modules/,
          loader: 'babel-loader'
        },
        {
          test: /\.woff2$/,
          loader: 'file-loader',
          options: {
            name: 'fonts/[name].[ext]'
          }
        },
        {
          test: /\.png$/,
          loader: 'file-loader',
          options: {
            name: 'images/[name].[ext]'
          }
        },
        {
          test: /\/manifest\.yml$/,
          use: [
            {
              loader: 'file-loader',
              options: {
                name: '[name].json'
              }
            },
            'extract-loader',
            {
              loader: 'chrome-manifest-loader',
              options: {
                mapVersion: true
              }
            },
            'yaml-loader'
          ]
        }
      ]
    },
    output: {
      path: path.resolve(__dirname, outputDir),
      filename: path.join('js', '[name].js')
    },
    plugins: [
      new CleanWebpackPlugin([outputDir]),
      new CopyWebpackPlugin([
        {
          context: sourceDir,
          from: path.join('_locales', '*', '*.json')
        },
        {
          from: 'LICENSE'
        }
      ]),
      ...R.map(
        (appName) =>
          new HtmlWebpackPlugin({
            chunks: [commonChunkName, appName],
            filename: `${appName}.html`,
            inject: 'body',
            minify: {
              collapseWhitespace: true,
              keepClosingSlash: true,
              minifyCSS: true,
              minifyJS: true,
              removeAttributeQuotes: true,
              removeCDATASectionsFromCDATA: true,
              removeComments: true,
              removeCommentsFromCDATA: true,
              removeScriptTypeAttributes: true,
              removeStyleTypeAttributes: true,
              useShortDoctype: true
            },
            title: pkg.name
          }),
        appNames
      ),
      new ScriptExtHtmlWebpackPlugin({
        defaultAttribute: 'defer'
      }),
      new webpack.DefinePlugin({
        'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
      }),
      new webpack.optimize.CommonsChunkPlugin(commonChunkName),
      new webpack.optimize.OccurrenceOrderPlugin(true)
    ],
    resolve: {
      alias: {
        'seamless-immutable': 'seamless-immutable/src/seamless-immutable',
        store: 'store/dist/store.modern'
      },
      extensions: ['.js', '.jsx']
    }
  },
  development: {
    devtool: 'source-map',
    module: {
      rules: [
        {
          test: /\.css$/,
          use: [
            'style-loader',
            {
              loader: 'css-loader',
              options: cssLoaderOptions
            },
            'postcss-loader'
          ]
        },
        {
          test: /\/icon.+\.png$/,
          loader: 'image-process-loader',
          options: {
            greyscale: true
          }
        }
      ]
    },
    watch: true
  },
  production: {
    module: {
      rules: [
        {
          test: /\.css$/,
          use: ExtractTextPlugin.extract({
            fallback: 'style-loader',
            publicPath: '../',
            use: [
              {
                loader: 'css-loader',
                options: cssLoaderOptions
              },
              'postcss-loader'
            ]
          })
        }
      ]
    },
    plugins: [
      new BundleAnalyzerPlugin({
        analyzerMode: 'static',
        reportFilename: path.join('..', '__report.html')
      }),
      new ExtractTextPlugin({
        filename: path.join('css', '[name].css'),
        allChunks: true
      }),
      new webpack.LoaderOptionsPlugin({
        minimize: true
      }),
      new UglifyJSPlugin({
        parallel: true,
        uglifyOptions: {
          compress: {
            drop_console: true,
            pure_getters: true,
            unsafe: true,
            unsafe_arrows: true,
            unsafe_comps: true,
            unsafe_Func: true,
            unsafe_math: true,
            unsafe_methods: true,
            unsafe_proto: true,
            unsafe_regexp: true
          },
          ecma: 6,
          output: {
            wrap_iife: true
          }
        }
      }),
      new ZipPlugin({
        filename: `${pkg.version}.zip`
      })
    ]
  }
})

module.exports = webpackConfig
<commit_msg>enable scope hoisting in webpack<commit_after>'use strict'

const CleanWebpackPlugin = require('clean-webpack-plugin')
const CopyWebpackPlugin = require('copy-webpack-plugin')
const ExtractTextPlugin = require('extract-text-webpack-plugin')
const HtmlWebpackPlugin = require('html-webpack-plugin')
const path = require('path')
const R = require('ramda')
const ScriptExtHtmlWebpackPlugin = require('script-ext-html-webpack-plugin')
const UglifyJSPlugin = require('uglifyjs-webpack-plugin')
const webpack = require('webpack')
const ZipPlugin = require('zip-webpack-plugin')
const {BundleAnalyzerPlugin} = require('webpack-bundle-analyzer')

const pkg = require('./package')
const {
  appNames, commonChunkName, outputDir, sourceDir
} = require('./config')

const getMergedConfigByEnv = R.converge(R.mergeDeepWith(R.concat), [
  R.prop('default'),
  R.propOr({}, process.env.NODE_ENV)
])

const cssLoaderOptions = {
  modules: true,
  importLoaders: 1,
  localIdentName: '[path]___[name]__[local]___[hash:base64:5]'
}

const webpackConfig = getMergedConfigByEnv({
  default: {
    entry: R.converge(R.zipObj, [R.identity, R.map(R.concat(`./${sourceDir}/js/`))])(appNames),
    module: {
      rules: [
        {
          test: /\.jsx?$/,
          exclude: /node_modules/,
          loader: 'babel-loader'
        },
        {
          test: /\.woff2$/,
          loader: 'file-loader',
          options: {
            name: 'fonts/[name].[ext]'
          }
        },
        {
          test: /\.png$/,
          loader: 'file-loader',
          options: {
            name: 'images/[name].[ext]'
          }
        },
        {
          test: /\/manifest\.yml$/,
          use: [
            {
              loader: 'file-loader',
              options: {
                name: '[name].json'
              }
            },
            'extract-loader',
            {
              loader: 'chrome-manifest-loader',
              options: {
                mapVersion: true
              }
            },
            'yaml-loader'
          ]
        }
      ]
    },
    output: {
      path: path.resolve(__dirname, outputDir),
      filename: path.join('js', '[name].js')
    },
    plugins: [
      new CleanWebpackPlugin([outputDir]),
      new CopyWebpackPlugin([
        {
          context: sourceDir,
          from: path.join('_locales', '*', '*.json')
        },
        {
          from: 'LICENSE'
        }
      ]),
      ...R.map(
        (appName) =>
          new HtmlWebpackPlugin({
            chunks: [commonChunkName, appName],
            filename: `${appName}.html`,
            inject: 'body',
            minify: {
              collapseWhitespace: true,
              keepClosingSlash: true,
              minifyCSS: true,
              minifyJS: true,
              removeAttributeQuotes: true,
              removeCDATASectionsFromCDATA: true,
              removeComments: true,
              removeCommentsFromCDATA: true,
              removeScriptTypeAttributes: true,
              removeStyleTypeAttributes: true,
              useShortDoctype: true
            },
            title: pkg.name
          }),
        appNames
      ),
      new ScriptExtHtmlWebpackPlugin({
        defaultAttribute: 'defer'
      }),
      new webpack.DefinePlugin({
        'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
      }),
      new webpack.optimize.CommonsChunkPlugin(commonChunkName),
      new webpack.optimize.ModuleConcatenationPlugin()
    ],
    resolve: {
      alias: {
        'seamless-immutable': 'seamless-immutable/src/seamless-immutable',
        store: 'store/dist/store.modern'
      },
      extensions: ['.js', '.jsx']
    }
  },
  development: {
    devtool: 'source-map',
    module: {
      rules: [
        {
          test: /\.css$/,
          use: [
            'style-loader',
            {
              loader: 'css-loader',
              options: cssLoaderOptions
            },
            'postcss-loader'
          ]
        },
        {
          test: /\/icon.+\.png$/,
          loader: 'image-process-loader',
          options: {
            greyscale: true
          }
        }
      ]
    },
    watch: true
  },
  production: {
    module: {
      rules: [
        {
          test: /\.css$/,
          use: ExtractTextPlugin.extract({
            fallback: 'style-loader',
            publicPath: '../',
            use: [
              {
                loader: 'css-loader',
                options: cssLoaderOptions
              },
              'postcss-loader'
            ]
          })
        }
      ]
    },
    plugins: [
      new BundleAnalyzerPlugin({
        analyzerMode: 'static',
        reportFilename: path.join('..', '__report.html')
      }),
      new ExtractTextPlugin({
        filename: path.join('css', '[name].css'),
        allChunks: true
      }),
      new webpack.LoaderOptionsPlugin({
        minimize: true
      }),
      new UglifyJSPlugin({
        parallel: true,
        uglifyOptions: {
          compress: {
            drop_console: true,
            pure_getters: true,
            unsafe: true,
            unsafe_arrows: true,
            unsafe_comps: true,
            unsafe_Func: true,
            unsafe_math: true,
            unsafe_methods: true,
            unsafe_proto: true,
            unsafe_regexp: true
          },
          ecma: 6,
          output: {
            wrap_iife: true
          }
        }
      }),
      new ZipPlugin({
        filename: `${pkg.version}.zip`
      })
    ]
  }
})

module.exports = webpackConfig
<|endoftext|>


<commit_before>/* eslint-disable */

const fs = require("fs");
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const WebpackBuildNotifierPlugin = require("webpack-build-notifier");
const ManifestPlugin = require("webpack-manifest-plugin");
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CopyWebpackPlugin = require("copy-webpack-plugin");
const LessPluginAutoPrefix = require("less-plugin-autoprefix");
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer")
  .BundleAnalyzerPlugin;

const path = require("path");

const isProduction = process.env.NODE_ENV === "production";

const redashBackend = process.env.REDASH_BACKEND || "http://localhost:5000";

const basePath = fs.realpathSync(path.join(__dirname, "client"));
const appPath = fs.realpathSync(path.join(__dirname, "client", "app"));

const extensionsRelativePath = process.env.EXTENSIONS_DIRECTORY ||
  path.join("client", "app", "extensions");
const extensionPath = fs.realpathSync(path.join(__dirname, extensionsRelativePath));

const config = {
  mode: isProduction ? "production" : "development",
  entry: {
    app: [
      "./client/app/index.js",
      "./client/app/assets/less/main.less",
      "./client/app/assets/less/ant.less"
    ],
    server: ["./client/app/assets/less/server.less"]
  },
  output: {
    path: path.join(basePath, "./dist"),
    filename: isProduction ? "[name].[chunkhash].js" : "[name].js",
    publicPath: "/static/"
  },
  resolve: {
    extensions: ['.js', '.jsx'],
    alias: {
      "@": appPath,
      "extensions": extensionPath
    }
  },
  plugins: [
    new WebpackBuildNotifierPlugin({ title: "Redash" }),
    // Enforce angular to use jQuery instead of jqLite
    new webpack.ProvidePlugin({ "window.jQuery": "jquery" }),
    // bundle only default `moment` locale (`en`)
    new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /en/),
    new HtmlWebpackPlugin({
      template: "./client/app/index.html",
      filename: "index.html",
      excludeChunks: ["server"]
    }),
    new HtmlWebpackPlugin({
      template: "./client/app/multi_org.html",
      filename: "multi_org.html",
      excludeChunks: ["server"]
    }),
    new MiniCssExtractPlugin({
      filename: "[name].[chunkhash].css"
    }),
    new ManifestPlugin({
      fileName: "asset-manifest.json",
      publicPath: "",
    }),
    new CopyWebpackPlugin([
      { from: "client/app/assets/robots.txt" },
      { from: "client/app/assets/css/*.css", to: "styles/", flatten: true },
      { from: "node_modules/jquery/dist/jquery.min.js", to: "js/jquery.min.js" }
    ])
  ],
  optimization: {
    splitChunks: {
      chunks: (chunk) => {
        return chunk.name != "server";
      }
    }
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: ["babel-loader", "eslint-loader"]
      },
      {
        test: /\.html$/,
        exclude: [/node_modules/, /index\.html/],
        use: [
          {
            loader: "raw-loader"
          }
        ]
      },
      {
        test: /\.css$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader
          },
          {
            loader: "css-loader",
            options: {
              minimize: process.env.NODE_ENV === "production"
            }
          }
        ]
      },
      {
        test: /\.less$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader
          },
          {
            loader: "css-loader",
            options: {
              minimize: process.env.NODE_ENV === "production"
            }
          },
          {
            loader: "less-loader",
            options: {
              plugins: [
                new LessPluginAutoPrefix({ browsers: ["last 3 versions"] })
              ],
              javascriptEnabled: true
            }
          }
        ]
      },
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        use: [
          {
            loader: "file-loader",
            options: {
              context: path.resolve(appPath, "./assets/images/"),
              outputPath: "images/",
              name: "[path][name].[ext]"
            }
          }
        ]
      },
      {
        test: /\.geo\.json$/,
        type: 'javascript/auto',
        use: [
          {
            loader: "file-loader",
            options: {
              outputPath: "data/",
              name: "[hash:7].[name].[ext]"
            }
          }
        ]
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        use: [
          {
            loader: "url-loader",
            options: {
              limit: 10000,
              name: "fonts/[name].[hash:7].[ext]"
            }
          }
        ]
      }
    ]
  },
  devtool: isProduction ? "source-map" : "cheap-eval-module-source-map",
  stats: {
    modules: false,
    chunkModules: false
  },
  watchOptions: {
    ignored: /\.sw.$/
  },
  devServer: {
    inline: true,
    index: "/static/index.html",
    historyApiFallback: {
      index: "/static/index.html",
      rewrites: [{ from: /./, to: "/static/index.html" }]
    },
    contentBase: false,
    publicPath: "/static/",
    proxy: [
      {
        context: [
          "/login",
          "/logout",
          "/invite",
          "/setup",
          "/status.json",
          "/api",
          "/oauth"
        ],
        target: redashBackend + "/",
        changeOrigin: false,
        secure: false
      },
      {
        context: path => {
          // CSS/JS for server-rendered pages should be served from backend
          return /^\/static\/[a-z]+\.[0-9a-fA-F]+\.(css|js)$/.test(path);
        },
        target: redashBackend + "/",
        changeOrigin: true,
        secure: false
      }
    ],
    stats: {
      modules: false,
      chunkModules: false
    }
  }
};

if (process.env.DEV_SERVER_HOST) {
  config.devServer.host = process.env.DEV_SERVER_HOST;
}

if (process.env.BUNDLE_ANALYZER) {
  config.plugins.push(new BundleAnalyzerPlugin());
}

module.exports = config;
<commit_msg>Fix webpack config to work with symlinks (#3573)<commit_after>/* eslint-disable */

const fs = require("fs");
const webpack = require("webpack");
const HtmlWebpackPlugin = require("html-webpack-plugin");
const WebpackBuildNotifierPlugin = require("webpack-build-notifier");
const ManifestPlugin = require("webpack-manifest-plugin");
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const CopyWebpackPlugin = require("copy-webpack-plugin");
const LessPluginAutoPrefix = require("less-plugin-autoprefix");
const BundleAnalyzerPlugin = require("webpack-bundle-analyzer")
  .BundleAnalyzerPlugin;

const path = require("path");

const isProduction = process.env.NODE_ENV === "production";

const redashBackend = process.env.REDASH_BACKEND || "http://localhost:5000";

const basePath = path.join(__dirname, "client");
const appPath = path.join(__dirname, "client", "app");

const extensionsRelativePath = process.env.EXTENSIONS_DIRECTORY ||
  path.join("client", "app", "extensions");
const extensionPath = path.join(__dirname, extensionsRelativePath);

const config = {
  mode: isProduction ? "production" : "development",
  entry: {
    app: [
      "./client/app/index.js",
      "./client/app/assets/less/main.less",
      "./client/app/assets/less/ant.less"
    ],
    server: ["./client/app/assets/less/server.less"]
  },
  output: {
    path: path.join(basePath, "./dist"),
    filename: isProduction ? "[name].[chunkhash].js" : "[name].js",
    publicPath: "/static/"
  },
  resolve: {
    symlinks: false,
    extensions: ['.js', '.jsx'],
    alias: {
      "@": appPath,
      "extensions": extensionPath
    },
  },
  plugins: [
    new WebpackBuildNotifierPlugin({ title: "Redash" }),
    // Enforce angular to use jQuery instead of jqLite
    new webpack.ProvidePlugin({ "window.jQuery": "jquery" }),
    // bundle only default `moment` locale (`en`)
    new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /en/),
    new HtmlWebpackPlugin({
      template: "./client/app/index.html",
      filename: "index.html",
      excludeChunks: ["server"]
    }),
    new HtmlWebpackPlugin({
      template: "./client/app/multi_org.html",
      filename: "multi_org.html",
      excludeChunks: ["server"]
    }),
    new MiniCssExtractPlugin({
      filename: "[name].[chunkhash].css"
    }),
    new ManifestPlugin({
      fileName: "asset-manifest.json",
      publicPath: "",
    }),
    new CopyWebpackPlugin([
      { from: "client/app/assets/robots.txt" },
      { from: "client/app/assets/css/*.css", to: "styles/", flatten: true },
      { from: "node_modules/jquery/dist/jquery.min.js", to: "js/jquery.min.js" }
    ])
  ],
  optimization: {
    splitChunks: {
      chunks: (chunk) => {
        return chunk.name != "server";
      }
    }
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: ["babel-loader", "eslint-loader"]
      },
      {
        test: /\.html$/,
        exclude: [/node_modules/, /index\.html/],
        use: [
          {
            loader: "raw-loader"
          }
        ]
      },
      {
        test: /\.css$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader
          },
          {
            loader: "css-loader",
            options: {
              minimize: process.env.NODE_ENV === "production"
            }
          }
        ]
      },
      {
        test: /\.less$/,
        use: [
          {
            loader: MiniCssExtractPlugin.loader
          },
          {
            loader: "css-loader",
            options: {
              minimize: process.env.NODE_ENV === "production"
            }
          },
          {
            loader: "less-loader",
            options: {
              plugins: [
                new LessPluginAutoPrefix({ browsers: ["last 3 versions"] })
              ],
              javascriptEnabled: true
            }
          }
        ]
      },
      {
        test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
        use: [
          {
            loader: "file-loader",
            options: {
              context: path.resolve(appPath, "./assets/images/"),
              outputPath: "images/",
              name: "[path][name].[ext]"
            }
          }
        ]
      },
      {
        test: /\.geo\.json$/,
        type: 'javascript/auto',
        use: [
          {
            loader: "file-loader",
            options: {
              outputPath: "data/",
              name: "[hash:7].[name].[ext]"
            }
          }
        ]
      },
      {
        test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
        use: [
          {
            loader: "url-loader",
            options: {
              limit: 10000,
              name: "fonts/[name].[hash:7].[ext]"
            }
          }
        ]
      }
    ]
  },
  devtool: isProduction ? "source-map" : "cheap-eval-module-source-map",
  stats: {
    modules: false,
    chunkModules: false
  },
  watchOptions: {
    ignored: /\.sw.$/
  },
  devServer: {
    inline: true,
    index: "/static/index.html",
    historyApiFallback: {
      index: "/static/index.html",
      rewrites: [{ from: /./, to: "/static/index.html" }]
    },
    contentBase: false,
    publicPath: "/static/",
    proxy: [
      {
        context: [
          "/login",
          "/logout",
          "/invite",
          "/setup",
          "/status.json",
          "/api",
          "/oauth"
        ],
        target: redashBackend + "/",
        changeOrigin: false,
        secure: false
      },
      {
        context: path => {
          // CSS/JS for server-rendered pages should be served from backend
          return /^\/static\/[a-z]+\.[0-9a-fA-F]+\.(css|js)$/.test(path);
        },
        target: redashBackend + "/",
        changeOrigin: true,
        secure: false
      }
    ],
    stats: {
      modules: false,
      chunkModules: false
    }
  }
};

if (process.env.DEV_SERVER_HOST) {
  config.devServer.host = process.env.DEV_SERVER_HOST;
}

if (process.env.BUNDLE_ANALYZER) {
  config.plugins.push(new BundleAnalyzerPlugin());
}

module.exports = config;
<|endoftext|>


<commit_before>const path = require('path');

module.exports = {
  entry: './client/src/app.jsx',
  output: {
    path: path.resolve(__dirname, 'resources/public'),
    filename: 'questionmark.js',
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        use: 'babel-loader',
      },
      {
        test: /\.json$/,
        use: 'json-loader',
      },
    ],
  },
};
<commit_msg>update webpack<commit_after>const path = require('path');
const CompressionPlugin = require('compression-webpack-plugin');

module.exports = {
  entry: ['./client/src/app.jsx'],
  output: {
    path: path.resolve(__dirname, 'resources/public/'),
    filename: 'questionmark.js',
  },
  module: {
    rules: [
      {
        test: /\.(js|jsx)$/,
        use: 'babel-loader',
      },
      {
        test: /\.json$/,
        use: 'json-loader',
      },
    ],
  },
  resolve: {
    extensions: ['.js', '.jsx'],
  },
  plugins: [
    new CompressionPlugin({
      asset: '[path].gz[query]',
      algorithm: 'gzip',
      test: /\.js$|\.css$|\.html$/,
      threshold: 10240,
      minRatio: 0.8,
    }),
  ],
};
<|endoftext|>


<commit_before>const path = require('path')

const webpack = require('webpack')
const BabiliPlugin = require('babili-webpack-plugin')
const clone = require('lodash/cloneDeep')
const LodashModuleReplacementPlugin = require('lodash-webpack-plugin')

const PROD = process.env.NODE_ENV === 'production'

const plugins = [
  new webpack.optimize.OccurrenceOrderPlugin(),
  new webpack.DefinePlugin({
    'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
  }),
  new LodashModuleReplacementPlugin({
    caching: true,
    cloning: true,
    memoizing: true
  })
]

if (PROD) {
  plugins.push(
    new BabiliPlugin()
  )
  plugins.push(
    new webpack.LoaderOptionsPlugin({
      minimize: true,
      debug: false
    })
  )
}

const baseFileName = `contentful`

const baseBundleConfig = {
  context: path.join(__dirname, 'lib'),
  entry: [`./${baseFileName}.js`],
  output: {
    path: path.join(__dirname, 'dist'),
    libraryTarget: 'umd',
    library: 'contentful'
  },
  module: {
    loaders: []
  },
  devtool: PROD ? false : 'source-map',
  plugins,
  node: {
    os: 'empty'
  },
  // Show minimal information, but all errors and warnings
  // Except for log generation which have to contain all information
  stats: process.env.WEBPACK_MODE === 'log' ? 'detailed' : {
    assets: true,
    cached: false,
    children: false,
    chunks: true,
    chunkModules: true,
    colors: true,
    errors: true,
    errorDetails: true,
    exclude: [],
    hash: false,
    maxModules: 0,
    modules: false,
    moduleTrace: false,
    performance: true,
    providedExports: true,
    publicPath: false,
    reasons: false,
    source: false,
    timings: true,
    usedExports: false,
    version: true,
    warnings: true
  }
}

const defaultBabelLoader = {
  test: /\.js?$/,
  include: [
    path.resolve(__dirname, 'lib'),
    path.resolve(__dirname, 'test')
  ],
  loader: 'babel-loader',
  options: {}
}

// Browsers
const browserBundle = clone(baseBundleConfig)
browserBundle.module.loaders = [
  Object.assign({}, defaultBabelLoader, {
    options: Object.assign({}, defaultBabelLoader.options, {
      forceEnv: 'browser'
    })
  })
]
browserBundle.output.filename = `${baseFileName}.browser${PROD ? '.min' : ''}.js`

// Legacy browsers like IE11
const legacyBundle = clone(baseBundleConfig)
legacyBundle.module.loaders = [
  Object.assign({}, defaultBabelLoader, {
    options: Object.assign({}, defaultBabelLoader.options, {
      forceEnv: 'legacy'
    })
  })
]
// To be replaced with babel-polyfill with babel-preset-env 2.0:
// https://github.com/babel/babel-preset-env#usebuiltins
// https://github.com/babel/babel-preset-env/pull/241
legacyBundle.entry = [
  'core-js/fn/promise',
  'core-js/fn/object/assign',
  'core-js/fn/array/from',
  'core-js/fn/array/find',
  'core-js/fn/set'
].concat(legacyBundle.entry)

legacyBundle.output.filename = `${baseFileName}.legacy${PROD ? '.min' : ''}.js`

// Node
const nodeBundle = clone(baseBundleConfig)
nodeBundle.module.loaders = [
  Object.assign({}, defaultBabelLoader, {
    options: Object.assign({}, defaultBabelLoader.options, {
      forceEnv: 'node'
    })
  })
]
nodeBundle.target = 'node'
nodeBundle.output.libraryTarget = 'commonjs2'
nodeBundle.output.filename = `${baseFileName}.node${PROD ? '.min' : ''}.js`
delete nodeBundle.node

module.exports = [
  browserBundle,
  legacyBundle,
  nodeBundle
]
<commit_msg>build(webpack): fix stats property to match webpack 3.8.0 schema<commit_after>const path = require('path')

const webpack = require('webpack')
const BabiliPlugin = require('babili-webpack-plugin')
const clone = require('lodash/cloneDeep')
const LodashModuleReplacementPlugin = require('lodash-webpack-plugin')

const PROD = process.env.NODE_ENV === 'production'

const plugins = [
  new webpack.optimize.OccurrenceOrderPlugin(),
  new webpack.DefinePlugin({
    'process.env.NODE_ENV': JSON.stringify(process.env.NODE_ENV)
  }),
  new LodashModuleReplacementPlugin({
    caching: true,
    cloning: true,
    memoizing: true
  })
]

if (PROD) {
  plugins.push(
    new BabiliPlugin()
  )
  plugins.push(
    new webpack.LoaderOptionsPlugin({
      minimize: true,
      debug: false
    })
  )
}

const baseFileName = `contentful`

const baseBundleConfig = {
  context: path.join(__dirname, 'lib'),
  entry: [`./${baseFileName}.js`],
  output: {
    path: path.join(__dirname, 'dist'),
    libraryTarget: 'umd',
    library: 'contentful'
  },
  module: {
    loaders: []
  },
  devtool: PROD ? false : 'source-map',
  plugins,
  node: {
    os: 'empty'
  },
  // Show minimal information, but all errors and warnings
  // Except for log generation which have to contain all information
  stats: process.env.WEBPACK_MODE === 'log' ? 'verbose' : 'normal'
}

const defaultBabelLoader = {
  test: /\.js?$/,
  include: [
    path.resolve(__dirname, 'lib'),
    path.resolve(__dirname, 'test')
  ],
  loader: 'babel-loader',
  options: {}
}

// Browsers
const browserBundle = clone(baseBundleConfig)
browserBundle.module.loaders = [
  Object.assign({}, defaultBabelLoader, {
    options: Object.assign({}, defaultBabelLoader.options, {
      forceEnv: 'browser'
    })
  })
]
browserBundle.output.filename = `${baseFileName}.browser${PROD ? '.min' : ''}.js`

// Legacy browsers like IE11
const legacyBundle = clone(baseBundleConfig)
legacyBundle.module.loaders = [
  Object.assign({}, defaultBabelLoader, {
    options: Object.assign({}, defaultBabelLoader.options, {
      forceEnv: 'legacy'
    })
  })
]
// To be replaced with babel-polyfill with babel-preset-env 2.0:
// https://github.com/babel/babel-preset-env#usebuiltins
// https://github.com/babel/babel-preset-env/pull/241
legacyBundle.entry = [
  'core-js/fn/promise',
  'core-js/fn/object/assign',
  'core-js/fn/array/from',
  'core-js/fn/array/find',
  'core-js/fn/set'
].concat(legacyBundle.entry)

legacyBundle.output.filename = `${baseFileName}.legacy${PROD ? '.min' : ''}.js`

// Node
const nodeBundle = clone(baseBundleConfig)
nodeBundle.module.loaders = [
  Object.assign({}, defaultBabelLoader, {
    options: Object.assign({}, defaultBabelLoader.options, {
      forceEnv: 'node'
    })
  })
]
nodeBundle.target = 'node'
nodeBundle.output.libraryTarget = 'commonjs2'
nodeBundle.output.filename = `${baseFileName}.node${PROD ? '.min' : ''}.js`
delete nodeBundle.node

module.exports = [
  browserBundle,
  legacyBundle,
  nodeBundle
]
<|endoftext|>