How to use webpack - 10 common examples

To help you get started, we’ve selected a few webpack examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github wuomzfx / tree-shaking-test / webpack.config.js View on Github external
const webpack = require('webpack')
const path = require('path')
const UglifyJsPlugin = require('uglifyjs-webpack-plugin')
const BabelPlugin = require('webpack-babel-plugin')

module.exports = {
  entry: './index.js',
  output: {
    path: path.resolve(__dirname, 'dist'),
    filename: 'webpack-bundle.js'
  },
  module: {
  },
  plugins: [
    new webpack.optimize.ModuleConcatenationPlugin(),
    // new webpack.optimize.UglifyJsPlugin({
    //   compress: {
    //     warnings: true,
    //     pure_getters: true
    //   },
    //   mangle: false,
    //   output: {
    //     beautify: true,
    //     indent_level: 2
    //   }
    // }),
    new UglifyJsPlugin({
      uglifyOptions: {
        compress: {
          warnings: true,
          pure_getters: true
github GooTechnologies / goojs / test / unit / karma.conf.js View on Github external
dir : 'coverage/'
		},

		webpackMiddleware: {
			// webpack-dev-middleware configuration
			// i. e.
			noInfo: true
		},

		webpack: {
			resolve: {
				// Everything relative to repo root
				root: path.resolve(path.join(__dirname, '..', '..'))
			},
			plugins: [
				new webpack.ProvidePlugin(require('./karmaWebpackProvidePluginSettings'))
			]
		}
	});
};
github skpm / skpm / packages / test-runner / lib / utils / update-webpack-config.js View on Github external
module.exports = (skpmConfig, getTestFiles, argv, logProgress) => config => {
  config.output.filename = 'compiled-tests.js'
  config.output.path = path.resolve(
    __dirname,
    '../../test-runner.sketchplugin/Contents/Sketch'
  )
  // https://webpack.js.org/configuration/output/#output-devtoolmodulefilenametemplate
  config.output.devtoolModuleFilenameTemplate = '[absolute-resource-path]'

  config.plugins.push(
    new webpack.ProvidePlugin({
      expect: require.resolve('../../expect'),
    })
  )

  if (!argv.buildOnly) {
    config.plugins.push(
      // eslint-disable-next-line
      new WebpackTestRunner({
        script: sketchtoolRunCommand(
          path.resolve(__dirname, '../../test-runner.sketchplugin'),
          'plugin-tests',
          {
            app: argv.app,
            withoutActivating: true,
            handleError: false,
          }
github zubairghori / Ultimate_todo_list / node_modules / webpack-dev-server / bin / webpack-dev-server.js View on Github external
function startDevServer(webpackOptions, options) {
  addDevServerEntrypoints(webpackOptions, options);

  let compiler;
  try {
    compiler = webpack(webpackOptions);
  } catch (e) {
    if (e instanceof webpack.WebpackOptionsValidationError) {
      console.error(colorError(options.stats.colors, e.message));
      process.exit(1); // eslint-disable-line
    }
    throw e;
  }

  if (options.progress) {
    compiler.apply(new webpack.ProgressPlugin({
      profile: argv.profile
    }));
  }

  const suffix = (options.inline !== false || options.lazy === true ? '/' : '/webpack-dev-server/');

  let server;
  try {
    server = new Server(compiler, options);
  } catch (e) {
    const OptionsValidationError = require('../lib/OptionsValidationError');
    if (e instanceof OptionsValidationError) {
      console.error(colorError(options.stats.colors, e.message));
          process.exit(1); // eslint-disable-line
    }
    throw e;
github ChartIQ / finsemble-seed / build / webpack / defaultWebpackConfig.js View on Github external
constructor() {
		let plugins =
			[
				new EnvironmentPlugin(['NODE_ENV']),
				new ProgressPlugin({ profile: false })
			]

		try {
			const VENDOR_MANIFEST = require('./vendor-manifest.json');
			plugins.push(new DllReferencePlugin({
				manifest: VENDOR_MANIFEST
			}));
		} catch (e) {
			//This should never happen. Vendor-manifest is built prior to files being built. But it's here just in case.
			console.error(`[WEBPACK ERROR:] You have not generated a vendor-manifest for your webpack configuration. This is an important optimization that reduces build times by 30-40%. Please run "npm run build:vendor-manifest", and then run "npm run dev" once more. You are required to build the vendor manifest when you delete your dist folder, when your node modules update, or when you update the Finsemble Seed project.`);
			process.exit(1);
		}

		if (env === "production") {
			// When building the production environment, minify the code.
			plugins.push(new UglifyJsPlugin());
		} else {
			plugins.push(new hardSource({
				//root dir here is "dist". Back out so we dump this file into the root.
				cacheDirectory: '../.webpack-file-cache/[confighash]',
				// Either an absolute path or relative to webpack's options.context.
github KochamCie / spring-boot-starter-quartz / src / main / frontend / build / webpack.prod.conf.js View on Github external
minify: {
        removeComments: true,
        collapseWhitespace: true,
        removeAttributeQuotes: true
        // more options:
        // https://github.com/kangax/html-minifier#options-quick-reference
      },
      // necessary to consistently work with multiple chunks via CommonsChunkPlugin
      chunksSortMode: 'dependency'
    }),
    // keep module.id stable when vendor modules does not change
    new webpack.HashedModuleIdsPlugin(),
    // enable scope hoisting
    new webpack.optimize.ModuleConcatenationPlugin(),
    // split vendor js into its own file
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      minChunks (module) {
        // any required modules inside node_modules are extracted to vendor
        return (
          module.resource &&
          /\.js$/.test(module.resource) &&
          module.resource.indexOf(
            path.join(__dirname, '../node_modules')
          ) === 0
        )
      }
    }),
    // extract webpack runtime and module manifest to its own file in order to
    // prevent vendor hash from being updated whenever app bundle is updated
    new webpack.optimize.CommonsChunkPlugin({
      name: 'manifest',
github axi-platform / legacy / web / tools / start.js View on Github external
/* eslint-disable no-param-reassign */
      config.entry = ["webpack-hot-middleware/client"].concat(config.entry)
      config.output.filename = config.output.filename.replace("[chunkhash]", "[hash]")
      config.output.chunkFilename = config.output.chunkFilename.replace("[chunkhash]", "[hash]")
      config.plugins.push(new webpack.HotModuleReplacementPlugin())
      config.plugins.push(new webpack.NoEmitOnErrorsPlugin())
      config.plugins.push(new DashboardPlugin())
    })

    // For other settings see
    // https://webpack.github.io/docs/webpack-dev-middleware

    let bundler

    try {
      bundler = webpack(webpackConfig)
    } catch (e) {
      console.error(e)
    }

    const wpMiddleware = webpackMiddleware(bundler, {
      publicPath: webpackConfig[0].output.publicPath,
      stats: webpackConfig[0].stats
    })

    const hotMiddlewares = bundler.compilers
      .filter(compiler => compiler.options.target !== "node")
      .map(compiler => webpackHotMiddleware(compiler))

    let handleServerBundleComplete = () => {
      runServer((err, host) => {
        if (!err) {
github edp963 / davinci / webapp / internals / webpack / webpack.base.babel.js View on Github external
limit: 10000
          }
        }
      }
    ]
  },
  plugins: options.plugins.concat([
    // Always expose NODE_ENV to webpack, in order to use `process.env.NODE_ENV`
    // inside your code for any environment checks; UglifyJS will automatically
    // drop any unreachable code.
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify(process.env.NODE_ENV)
      }
    }),
    new webpack.ContextReplacementPlugin(/^\.\/locale$/, (context) => {
      if (!/\/moment\//.test(context.context)) return;

      Object.assign(context, {
          regExp: /^\.\/\w+/,
          request: '../../locale', // resolved relatively
      });
    }),
    new webpack.ProvidePlugin({
      'window.Quill': 'quill'
    }),
    new HappyPack({
      id: 'typescript',
      loaders: options.tsLoaders,
      threadPool: happyThreadPool,
      verbose: true
    }),
github cdmbase / fullstack-pro / tools / webpack.run.js View on Github external
function startServer() {
  try {
    const reporter = (...args) => webpackReporter(logBack, ...args);

    if (__DEV__) {
      _.each(serverConfig.entry, entry => {
        if (__WINDOWS__) {
          entry.push('webpack/hot/poll?1000');
        } else {
          entry.push('webpack/hot/signal.js');
        }
      });
      serverConfig.plugins.push(new webpack.HotModuleReplacementPlugin(),
        new webpack.NoEmitOnErrorsPlugin());
    }

    const compiler = webpack(serverConfig);

    if (__DEV__) {
      compiler.plugin('compilation', compilation => {
        compilation.plugin('after-optimize-assets', assets => {
          // Patch webpack-generated original source files path, by stripping hash after filename
          const mapKey = _.findKey(assets, (v, k) => k.endsWith('.map'));
          if (mapKey) {
            var srcMap = JSON.parse(assets[mapKey]._value);
            for (var idx in srcMap.sources) {
              srcMap.sources[idx] = srcMap.sources[idx].split(';')[0];
            }
            assets[mapKey]._value = JSON.stringify(srcMap);
          }
github js-joda / js-joda / utils / build_package.js View on Github external
webpackConfig = Object.keys(argv.packages).map((key) => {
        const locales = argv.packages[key];
        const output = path.resolve(path.resolve(process.cwd(), argv.output, key));
        return createWebpackConfig(locales, output);
    });
}

if (webpackConfig) {
    RegExp.prototype.toJSON = RegExp.prototype.toString;
    /* eslint-disable no-console */
    if (argv.debug) {
        console.log(JSON.stringify(webpackConfig, null, 4));
    }
    const webpackCompiler = webpack(webpackConfig);

    webpackCompiler.apply(new webpack.ProgressPlugin());

    webpackCompiler.run((err, stats) => {
        if (err) {
            console.error(err.stack || err);
            if (err.details) {
                console.error(err.details);
            }
            return;
        }

        const info = stats.toJson();

        if (stats.hasErrors()) {
            console.error(info.errors);
        }