30 Answers from Stack Overflow to the most popular webpack questions

Learn webpack and common issues by exploring 30 questions and answers!

Image for post?A child playing with a Jenga block tower? by Micha? Parzuchowski on Unsplash

Have you seen in webpack site (https://webpack.js.org/vote/) there is a page where you can influence and rank the priority of the new features that need to come out in the next versions of webpack? The highest vote is of course the first priority.

Image for postfrom https://webpack.js.org/vote/

So, I decided to contribute to this amazing community by collecting and analyzing questions and answers that most users ask there and writing them in this article.

After you read this article, you will have a deep insight into the most common issues on webpack.

Your feedback is matters.

Share and help me make this article a source of knowledge for our community.

If you think that there is a missing question that should be added to the article or that there is a question that is no longer relevant, please let me know.

Great appreciation,

Shlomi Levi (@wizardnet972) | Twitter

The latest Tweets from Shlomi Levi (@wizardnet972). #web-stuff wizardnet972@github. israel

twitter.com

Table of Contents

  • ? NPM vs. Bower vs. Browserify vs. Gulp vs. Grunt vs. Webpack
  • ? How to bundle an Angular app for production
  • ? What are differences between SystemJS and Webpack?
  • ? How to add font-awesome to Angular 2 + CLI project
  • ? How to load image files with webpack file-loader
  • ? Can someone explain Webpack?s CommonsChunkPlugin
  • ? Angular2 CLI huge vendor bundle: how to improve size for prod?
  • ? HtmlWebpackPlugin injects relative path files which breaks when loading non-root website paths
  • ? Webpack how to build production code and how to use it
  • ? webpack is not recognized as a internal or external command,operable program or batch file
  • ? How to create multiple output paths in Webpack config
  • ? How to add fonts to create-react-app based projects?
  • ? webpack can?t find module if file named jsx
  • ? How to debug Angular with VSCode?
  • ? Path aliases for imports in WebStorm
  • ? Webpack-dev-server compiles files but does not refresh or make compiled javascript available to browser
  • ? Webpack loaders vs plugins; what?s the difference?
  • ? Webpack vs webpack-dev-server vs webpack-dev-middleware vs webpack-hot-middleware vs etc
  • ? Error: Cannot resolve module ?style-loader?
  • ? Angular2: import external js file into component
  • ? Correct path for img on React.js
  • ? How to deploy node that uses Webpack to heroku
  • ? Webpack import returns undefined, depending on the order of imports
  • ? Serving static assets in webpack dev server
  • ? Conflict: Multiple assets emit to the same filename
  • ? Is it possible to write webpack config in typescript?
  • ? How to minify ES6 code using Webpack?
  • ? What is the value of using Webpack with HTTP/2
  • ? How to use images in css with Webpack
  • ? Avoiding relative paths in Angular CLI

? NPM vs. Bower vs. Browserify vs. Gulp vs. Grunt vs. Webpack

? Question got 1,428+ points, answer got 746+ points ????? 218,452+ viewed

Volodymyr Bakhmatiuk asked, I?m trying to summarize my knowledge about the most popular JavaScript package managers, bundlers, and task runners. Please correct me if I?m wrong:

  • npm & bower are package managers. They just download the dependencies and don’t know how to build projects on their own. What they know is to call webpack/gulp/grunt after fetching all the dependencies.
  • bower is like npm, but builds flattened dependencies trees (unlike npm which do it recursively). Meaning npm fetches the dependencies for each dependency (may fetch the same a few times), while bower expects you to manually include sub-dependencies. Sometimes bower and npm are used together for front-end and back-end respectively (since each megabyte might matter on front-end).
  • grunt and gulp are task runners to automate everything that can be automated (i.e. compile CSS/Sass, optimize images, make a bundle and minify/transpile it).
  • grunt vs. gulp (is like maven vs. gradle or configuration vs. code). Grunt is based on configuring separate independent tasks, each task opens/handles/closes file. Gulp requires less amount of code and is based on Node streams, which allows it to build pipe chains (w/o reopening the same file) and makes it faster.
  • webpack (webpack-dev-server) – for me it’s a task runner with hot reloading of changes which allows you to forget about all JS/CSS watchers.
  • npm/bower + plugins may replace task runners. Their abilities often intersect so there are different implications if you need to use gulp/grunt over npm + plugins. But task runners are definitely better for complex tasks (e.g. “on each build create bundle, transpile from ES6 to ES5, run it at all browsers emulators, make screenshots and deploy to dropbox through ftp”).
  • browserify allows packaging node modules for browsers. browserify vs node’s require is actually AMD vs CommonJS.

Questions:

  1. What is webpack & webpack-dev-server? Official documentation says it’s a module bundler but for me it’s just a task runner. What’s the difference?
  2. Where would you use browserify? Can’t we do the same with node/ES6 imports?
  3. When would you use gulp/grunt over npm + plugins?
  4. Please provide examples when you need to use a combination

???

? Answered by Dan Macák ? ? ?

Webpack and Browserify

Webpack and Browserify do pretty much the same job, which is processing your code to be used in a target environment (mainly browser, though you can target other environments like Node). Result of such processing is one or more bundles ? assembled scripts suitable for targeted environment. For example, let?s say you wrote an ES6 code divided into modules and want be able to run it in browser. If those modules are Node modules, browser won?t understand them since they exist only in Node environment. ES6 modules also won?t work in older browsers like IE11. Moreover you might have used experimental language features (ES next proposals) that browsers don?t implement yet so running such script would just throw errors. Those tools like Webpack and Browserify solve these problems by translating such code to a form browser is able to execute. On top of that, they make it possible to apply a huge variety of optimisations on those bundles.However, Webpack and Browserify differ in many ways, Webpack offers many tools by default (e.g. code splitting), while Browserify can do this only after downloading plugins but using both leads to very similar results. It comes down to personal preference (Webpack is trendier). Btw, Webpack is not a task runner, it is just processor of your files (it processes them by so called loaders and plugins) and it can be run (among other ways) by a task runner.

Webpack Dev Server

Webpack Dev Server provides similar solution to Browsersync ? a development server where you can deploy your app rapidly as you are working on it, and verify your development progress immediately with the dev server automatically refreshing the browser on code changes or even propagating changed code to browser without reloading with so called hot module replacement.

Task runners vs NPM scripts

I?ve been using Gulp for its conciseness and easy task writing, but have later found out I need neither Gulp nor Grunt at all. Everything I have ever needed could have been done using NPM scripts to run 3rd-party tools through their API. Choosing between Gulp, Grunt or NPM scripts depends on taste and experience of your team.While tasks in Gulp or Grunt are easy to read even for people not so familiar with JS, it is yet another tool to require and learn and I personally prefer to narrow my dependencies and make things simple. On the other hand, replacing these tasks with the combination of NPM scripts and (propably JS) scripts which run those 3rd party tools (eg. Node script configuring and running rimraf for cleaning purposes) might be more challenging. But in the majority of cases, those three are equal in terms of results.

Examples

As for the examples, I suggest you have a look at this React starter project, which shows you a nice combination of NPM and JS scripts covering the whole build and deploy process. You can find those NPM scripts in package.json in the root folder, in a property named scripts. There you will mostly encounter commands like babel-node tools/run start. Babel-node is a CLI tool (not meant for production use), which at first compiles ES6 file tools/run (run.js file located in tools) – basically a runner utility. This runner takes a function as an argument and executes it, which in this case is start – another utility (start.js) responsible for bundling source files (both client and server) and starting the application and development server (the dev server will be probably either Webpack Dev Server or Browsersync).Speaking more precisely, start.js creates both client and server side bundles, starts express server and after successful start inits Browser-sync, which at the time of writing looked like this (please refer to react starter project for the newest code).

const bs = Browsersync.create(); bs.init({ …(DEBUG ? {} : { notify: false, ui: false }), proxy: { target: host, middleware: [wpMiddleware, …hotMiddlewares], }, // no need to watch ‘*.js’ here, webpack will take care of it for us, // including full page reloads if HMR won’t work files: [‘build/content/**/*.*’],}, resolve)

The important part is proxy.target, where they set server address they want to proxy, which could be http://localhost:3000, and Browsersync starts a server listening on http://localhost:3001, where the generated assets are served with automatic change detection and hot module replacement. As you can see, there is another configuration property fileswith individual files or patterns Browser-sync watches for changes and reloads the browser if some occur, but as the comment says, Webpack takes care of watching js sources by itself with HMR, so they cooperate there.Now I don’t have any equivalent example of such Grunt or Gulp configuration, but with Gulp (and somewhat similarly with Grunt) you would write individual tasks in gulpfile.js like

gulp.task(‘bundle’, function() { // bundling source files with some gulp plugins like gulp-webpack maybe});gulp.task(‘start’, function() { // starting server and stuff});

where you would be doing essentially pretty much the same things as in the starter-kit, this time with task runner, which solves some problems for you, but presents its own issues and some difficulties during learning the usage, and as I say, the more dependencies you have, the more can go wrong. And that is the reason I like to get rid of such tools.

NPM vs. Bower vs. Browserify vs. Gulp vs. Grunt vs. Webpack

I’ve been also searching for this quite some time since there is a lot of tools out there and each of them benefits us?

stackoverflow.com

Top ???

? How to bundle an Angular app for production

? Question got 269+ points, answer got 276+ points ????? 120,173+ viewed

Pat M asked, I would like to track and update in this thread the latest best (and hopefully the simplest) method to bundle Angular (version 2, 4, ?) for production on a live web server.Please include the Angular version within answers so we can track better when it moves to later releases.

???

? Answered by Nicolas Henneaux ? ? ?

2.x, 4.x, 5.x, 6.x (TypeScript) with Angular CLI

OneTime Setup

  • npm install -g @angular/cli
  • ng new projectFolder creates a new application

Bundling Step

  • ng build –prod (run in command line when directory is projectFolder)flag prod bundle for production (see the Angular documentation for the list of option included with the production flag).
  • Compress using Brotli compression the resources using the following command for i in dist/*; do brotli $i; done

bundles are generated by default to projectFolder/dist(/$projectFolder for 6)

Output

Sizes with Angular 6.0.0 with CLI 6.0.0

  • dist/main.[hash].bundle.js Your application bundled [ size: 149 KB for new Angular CLI application empty, 36 KB compressed].
  • dist/polyfill.[hash].bundle.js the polyfill dependencies (@angular, RxJS…) bundled [ size: 58 KB for new Angular CLI application empty, 17 KB compressed].
  • dist/index.html entry point of your application.
  • dist/inline.[hash].bundle.js webpack loader
  • dist/style.[hash].bundle.css the style definitions
  • dist/assets resources copied from the Angular CLI assets configuration

Deployment

You can get a preview of your application using the ng serve –prod command that starts a local HTTP server such that the application with production files is accessible using http://localhost:4200.For a production usage, you have to deploy all the files from the dist folder in the HTTP server of your choice.

How to bundle an Angular app for production

I would like to track and update in this thread the latest best (and hopefully the simplest) method to bundle Angular?

stackoverflow.com

Top ???

? What are differences between SystemJS and Webpack?

? Question got 162+ points, answer got 102+ points ????? 63,844+ viewed

smartmouse asked, I?m creating my first Angular application and I would figure out what is the role of the module loaders. Why we need them? I tried to search and search on Google and I can?t understand why we need to install one of them to run our application?Couldn?t it be enough to just use import to load stuff from node modules?I have followed this tutorial (that uses SystemJS) and it makes me to use systemjs.config.js file:

/** * System configuration for Angular samples * Adjust as necessary for your application needs. */(function(global) { // map tells the System loader where to look for things var map = { ‘app’: ‘transpiled’, // ‘dist’, ‘@angular’: ‘node_modules/@angular’, ‘angular2-in-memory-web-api’: ‘node_modules/angular2-in-memory-web-api’, ‘rxjs’: ‘node_modules/rxjs’ }; // packages tells the System loader how to load when no filename and/or no extension var packages = { ‘app’: { main: ‘main.js’, defaultExtension: ‘js’ }, ‘rxjs’: { defaultExtension: ‘js’ }, ‘angular2-in-memory-web-api’: { main: ‘index.js’, defaultExtension: ‘js’ }, }; var ngPackageNames = [ ‘common’, ‘compiler’, ‘core’, ‘forms’, ‘http’, ‘platform-browser’, ‘platform-browser-dynamic’, ‘router’, ‘router-deprecated’, ‘upgrade’, ]; // Individual files (~300 requests): function packIndex(pkgName) { packages[‘@angular/’+pkgName] = { main: ‘index.js’, defaultExtension: ‘js’ }; } // Bundled (~40 requests): function packUmd(pkgName) { packages[‘@angular/’+pkgName] = { main: ‘/bundles/’ + pkgName + ‘.umd.js’, defaultExtension: ‘js’ }; } // Most environments should use UMD; some (Karma) need the individual index files var setPackageConfig = System.packageWithIndex ? packIndex : packUmd; // Add package entries for angular packages ngPackageNames.forEach(setPackageConfig); var config = { map: map, packages: packages }; System.config(config);})(this);

Why we need this configuration file?Why we need SystemJS (or WebPack or others)?Finally, in your opinion what is the better?

???

? Answered by Thierry Templier ? ? ?

If you go to the SystemJS Github page, you will see the description of the tool:

Universal dynamic module loader – loads ES6 modules, AMD, CommonJS and global scripts in the browser and NodeJS.

Because you use modules in TypeScript or ES6, you need a module loader. In the case of SystemJS, the systemjs.config.js allows us to configure the way in which module names are matched with their corresponding files.This configuration file (and SystemJS) is necessary if you explicitly use it to import the main module of your application:

<script> System.import(‘app’).catch(function(err){ console.error(err); });</script>

When using TypeScript, and configuring the compiler to the commonjs module, the compiler creates code that is no longer based on SystemJS. In this example, the typescript compiler config file would appear like this:

{ “compilerOptions”: { “target”: “es5”, “module”: “commonjs”, // <—— “moduleResolution”: “node”, “sourceMap”: true, “emitDecoratorMetadata”: true, “experimentalDecorators”: true, “removeComments”: false, “noImplicitAny”: false }}

Webpack is a flexible module bundler. This means that it goes further and doesn?t only handle modules but also provides a way to package your application (concat files, uglify files, ?). It also provides a dev server with load reload for developmentSystemJS and Webpack are different but with SystemJS, you still have work to do (with Gulp or SystemJS builder for example) to package your Angular2 application for production.

What are differences between SystemJS and Webpack?

SystemJS works client side. It loads modules (files) dynamically on demand when they are needed. You don’t have to load?

stackoverflow.com

Top ???

? How to add font-awesome to Angular 2 + CLI project

? Question got 149+ points, answer got 313+ points ????? 84,403+ viewed

Nik asked, I?m using Angular 2+ and Angular CLI.How do I add font-awesome to my project?

???

? Answered by AIon ? ? ?

After Angular 2.0 final release, the structure of the Angular2 CLI project has been changed ? you don?t need any vendor files, no system.js ? only webpack. So you do:

  1. npm install font-awesome –save
  2. In the angular-cli.json file locate the styles array and add font-awesome references directory here, like below:

“apps”: [ { “root”: “src”, “outDir”: “dist”, …. “styles”: [ “styles.css”, “../node_modules/bootstrap/dist/css/bootstrap.css”, “../node_modules/font-awesome/css/font-awesome.css” // -here webpack will automatically build a link css element out of this!? ], … } ]],

  1. Place some font-awesome icons in any html file you want: `<i class=?fa fa-american-sign-language-interpreting fa-5x? aria-hidden=?true?> </i>`
  2. Stop the application Ctrl + c then re-run the app using ng serve because the watchers are only for the src folder and angular-cli.json is not observed for changes.
  3. Enjoy your awesome icons!

How to add font-awesome to Angular 2 + CLI project

Edit: I’m using angular ^4.0.0 and Electron ^1.4.3 If you have issues with ElectronJS or similar and have a sort of 404?

stackoverflow.com

Top ???

? How to load image files with webpack file-loader

? Question got 81+ points, answer got 129+ points ????? 80,194+ viewed

Zhao Yi asked, I am using webpack to manage a reactjs project. I want to load images in javascript by webpack file-loader. Below is the webpack.config.js:

const webpack = require(‘webpack’);const path = require(‘path’);const NpmInstallPlugin = require(‘npm-install-webpack-plugin’);const PATHS = { react: path.join(__dirname, ‘node_modules/react/dist/react.min.js’), app: path.join(__dirname, ‘src’), build: path.join(__dirname, ‘./dist’)};module.exports = { entry: { jsx: ‘./app/index.jsx’, }, output: { path: PATHS.build, filename: ‘app.bundle.js’, }, watch: true, devtool: ‘eval-source-map’, relativeUrls: true, resolve: { extensions: [”, ‘.js’, ‘.jsx’, ‘.css’, ‘.less’], modulesDirectories: [‘node_modules’], alias: { normalize_css: __dirname + ‘/node_modules/normalize.css/normalize.css’, } }, module: { preLoaders: [ { test: /.js$/, loader: “source-map-loader” }, ], loaders: [ { test: /.html$/, loader: ‘file?name=[name].[ext]’, }, { test: /.jsx?$/, exclude: /node_modules/, loader: ‘babel-loader?presets=es2015’, }, {test: /.css$/, loader: ‘style-loader!css-loader’}, {test: /.(jpe?g|png|gif|svg)$/i, loader: “file-loader?name=/public/icons/[name].[ext]”}, { test: /.js$/, exclude: /node_modules/, loaders: [‘babel-loader?presets=es2015’] } ] }, plugins: [ new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false, }, output: { comments: false, }, }), new NpmInstallPlugin({ save: true // –save }), new webpack.DefinePlugin({ “process.env”: { NODE_ENV: JSON.stringify(“production”) } }), ], devServer: { colors: true, contentBase: __dirname, historyApiFallback: true, hot: true, inline: true, port: 9091, progress: true, stats: { cached: false } }}

I use this line to load image files and copy them to dist/public/icons directory and keep the same file name.

{test: /.(jpe?g|png|gif|svg)$/i, loader: “file-loader?name=/public/icons/[name].[ext]”}

But I have two problems on using it. When I run webpack command, the image file was copied to dist/public/icons/ directory as expected. How, ver it was also copied to dist directory with this file name “df55075baa16f3827a57549950901e90.png”. Below is my project structure:

Image for post

Another problem is that I use below code to import this image file but it couldn?t show on the browser. If I am using url ?public/icons/imageview_item_normal.png? on the img tag, it works fine. How to use the object imported from the image file?

import React, {Component} from ‘react’;import {render} from ‘react-dom’;import img from ‘file!../../public/icons/imageview_item_normal.png’export default class MainComponent extends Component { render() { return ( <div style={styles.container}> download <img src={img}/> </div> ) }}const styles = { container: { width: ‘100%’, height: ‘100%’, }}

???

? Answered by omerts ? ? ?

Regarding problem #1

Once you have the file-loader configured in the webpack.config, whenever you use import/require it tests the path against all loaders, and in case there is a match it passes the contents through that loader. In your case, it matched

{ test: /.(jpe?g|png|gif|svg)$/i, loader: “file-loader?name=/public/icons/[name].[ext]”}

and therefore you see the image emitted to

dist/public/icons/imageview_item_normal.png

which is the wanted behavior. The reason you are also getting the hash file name, is because you are adding an additional inline file-loader. You are importing the image as:

‘file!../../public/icons/imageview_item_normal.png’.

Prefixing with file!, passes the file into the file-loader again, and this time it doesn’t have the name configuration.So your import should really just be:

import img from ‘../../public/icons/imageview_item_normal.png’

UpdateAs noted by @cgatian, if you actually want to use an inline file-loader, ignoring the webpack global configuration, you can prefix the import with two exclamation marks (!!):

import ‘!!file!../../public/icons/imageview_item_normal.png’.

Regarding problem #2

After importing the png, the img variable only holds the path the file-loader “knows about”, which is public/icons/[name].[ext] (aka “file-loader? name=/public/icons/[name].[ext]”). Your output dir “dist” is unknown. You could solve this in two ways:

  1. Run all your code under the ?dist? folder
  2. Add publicPath property to your output config, that points to your output directory (in your case ./dist).

Example:

output: { path: PATHS.build, filename: ‘app.bundle.js’, publicPath: PATHS.build},

How to load image files with webpack file-loader

I am using webpack to manage a reactjs project. I want to load images in javascript by webpack file-loader. Below is?

stackoverflow.com

Top ???

? Can someone explain Webpack?s CommonsChunkPlugin

? Question got 69+ points, answer got 91+ points ????? 6,595+ viewed

Dimitris Karagiannis asked, I get the general gist that the CommonsChunkPlugin looks at all the entry points, checks to see if there are common packages/dependencies between them and separates them into their own bundle.So, let’s assume I have the following configuration:

…enrty : { entry1 : ‘entry1.js’, //which has ‘jquery’ as a dependency entry2 : ‘entry2.js’, //which has ‘jquery as a dependency vendors : [ ‘jquery’, ‘some_jquery_plugin’ //which has ‘jquery’ as a dependency ]},output: { path: PATHS.build, filename: ‘[name].bundle.js’}…

If I bundle without using CommonsChunkPlugin

I will end up with 3 new bundle files:

  • entry1.bundle.js which contains the complete code from entry1.js and jquery and contains its own runtime
  • entry2.bundle.js which contains the complete code from entry2.js and jquery and contains its own runtime
  • vendors.bundle.js which contains the complete code from jquery and some_jquery_plugin and contains its own runtime

This is obviously bad because I will potentially load jquery 3 times in the page, so we don’t want that.

If I bundle using CommonsChunkPlugin

Depending on what arguments I pass to CommonsChunkPlugin any of the following will happen:

  • CASE 1 : If I pass { name : ‘commons’ } I will end up with the following bundle files:
  • entry1.bundle.js which contains the complete code from entry1.js, a requirement for jquery and does not contain the runtime
  • entry2.bundle.js which contains the complete code from entry2.js, a requirement for jquery and does not contain the runtime
  • vendors.bundle.js which contains the complete code from some_jquery_plugin, a requirement for jquery and does not contain the runtime
  • commons.bundle.js which contains the complete code from jquery and contains the runtime
  • This way we end up with some smaller bundles overall and the runtime is contained in the commons bundle. Pretty ok but not ideal.
  • CASE 2 : If I pass { name : ‘vendors’ } I will end up with the following bundle files:
  • entry1.bundle.js which contains the complete code from entry1.js, a requirement for jquery and does not contain the runtime
  • entry2.bundle.js which contains the complete code from entry2.js, a requirement for jquery and does not contain the runtime
  • vendors.bundle.js which contains the complete code from jquery and some_jquery_plugin and contains the runtime.
  • This way, again, we end up with some smaller bundles overall but the runtime is now contained in the vendors bundle. It’s a little worse than the previous case, since the runtime is now in the vendors bundle.
  • CASE 3 : If I pass { names : [‘vendors’, ‘manifest’] } I will end up with the following bundle files:
  • entry1.bundle.js which contains the complete code from entry1.js, a requirement for jquery and does not contain the runtime
  • entry2.bundle.js which contains the complete code from entry2.js, a requirement for jquery and does not contain the runtime
  • vendors.bundle.js which contains the complete code from jquery and some_jquery_plugin and does not contain the runtime
  • manifest.bundle.js which contains requirements for every other bundle and contains the runtime
  • This way we end up with some smaller bundles overall and the runtime is contained in the manifest bundle. This is the ideal case.

What I do not understand/I am not sure I understand

  • In CASE 2 why did we end up with the vendors bundle containing both the common code (jquery) and whatever remained from the vendors entry (some_jquery_plugin)? From my understanding, what the CommonsChunkPlugin did here was that it gathered the common code (jquery), and since we forced it to output it to the vendors bundle, it kind of “merged” the common code into the vendors bundle (which now only contained the code from some_jquery_plugin). Please confirm or explain.
  • In CASE 3 I do not understand what happened when we passed { names : [‘vendors’, ‘manifest’] } to the plugin. Why/how was the vendors bundle kept intact, containing both jquery and some_jquery_plugin, when jquery is clearly a common dependency, and why was the generated manifest.bundle.js file created the way it was created (requiring all other bundles and containing the runtime) ?

???

? Answered by Laurent Etiemble ? ? ?

This is how the CommonsChunkPlugin works.A common chunk “receives” the modules shared by several entry chunks. A good example of a complex configuration can be found in the Webpack repository.The CommonsChunkPlugin is run during the optimization phase of Webpack, which means that it operates in memory, just before the chunks are sealed and written to the disk.When several common chunks are defined, they are processed in order. In your case 3, it is like running the plugin twice. But please note that the CommonsChunkPlugin can have a more complex configuration (minSize, minChunks, etc) that impacts the way modules are moved.CASE 1:

  1. There are 3 entry chunks (entry1, entry2 and vendors).
  2. The configuration sets the commons chunk as a common chunk.
  3. The plugin processes the commons common chunk (since the chunk does not exist, it is created):
  4. It collects the modules that are used more than once in the other chunks: entry1, entry2 and vendors use jquery so the module is removed from these chunks and is added to the commons chunk.
  5. The commons chunk is flagged as an entry chunk while the entry1, entry2 and vendors chunks are unflagged as entry.
  6. Finally, since the commons chunk is an entry chunk it contains the runtime and the jquery module.

CASE 2:

  1. There are 3 entry chunks (entry1, entry2 and vendors).
  2. The configuration sets the vendors chunk as a common chunk.
  3. The plugin processes the vendors common chunk:
  4. It collects the modules that are used more than once in the other chunks: entry1 and entry2 use jquery so the module is removed from these chunks (note that it is not added to the vendors chunk because the vendors chunk already contains it).
  5. The vendors chunk is flagged as an entry chunk while the entry1 and entry2 chunks are unflagged as entry.
  6. Finally, since the vendors chunk is an entry chunk, it contains the runtime and the jquery/jquery_plugin modules.

CASE 3:

  1. There are 3 entry chunks (entry1, entry2 and vendors).
  2. The configuration sets the vendors chunk and the manifest chunk as common chunks.
  3. The plugin creates the manifest chunk as it does not exist.
  4. The plugin processes the vendors common chunk:
  5. It collects the modules that are used more than once in the other chunks: entry1 and entry2 use jquery so the module is removed from these chunks (note that it is not added to the vendors chunk because the vendors chunk already contains it).
  6. The vendors chunk is flagged as an entry chunk while the entry1 and entry2 chunks are unflagged as entry.
  7. The plugin processes the manifest common chunk (since the chunk does not exist, it is created):
  8. It collects the modules that are used more than once in the other chunks: as there are no modules used more than once, no module is moved.
  9. The manifest chunk is flagged as entry chunk while the entry1, entry2 and vendors are unflagged as entry.
  10. Finally, since the manifest chunk is an entry chunk it contains the runtime.

Hope it helps.

Can someone explain Webpack’s CommonsChunkPlugin

I get the general gist that the CommonsChunkPlugin looks at all the entry points, checks to see if there are common?

stackoverflow.com

Top ???

? Angular2 CLI huge vendor bundle: how to improve size for prod?

? Question got 66+ points, answer got 19+ points ????? 32,685+ viewed

BlackHoleGalaxy asked, I have a simple app, initialized by angular-cli.It display some pages relative to 3 routes. I have 3 components. On one of this page I use lodash and Angular2 Http modules to get some data (using Rxjs Observables, map and subscribe). I display these elements using a simple ngFor.But, despite the fact my app is really simple, I get a HUGE (in my opinion) bundle package and maps. I don’t talk about gzip versions though but size before gzipping. This question is just a general recommendations ask.Some tests results:ng build

Hash: 8efac7d6208adb8641c1 Time: 10129ms chunk {0} main.bundle.js, main.bundle.map (main) 18.7 kB {3} [initial] [rendered] chunk {1} styles.bundle.css, styles.bundle.map, styles.bundle.map (styles) 155 kB {4} [initial] [rendered] chunk {2} scripts.bundle.js, scripts.bundle.map (scripts) 128 kB {4} [initial] [rendered] chunk {3} vendor.bundle.js, vendor.bundle.map (vendor) 3.96 MB [initial] [rendered] chunk {4} inline.bundle.js, inline.bundle.map (inline) 0 bytes [entry] [rendered]

Wait: 10Mb vendor bundle package for such a simple app?ng build ? prod

Hash: 09a5f095e33b2980e7cc Time: 23455ms chunk {0} main.6273b0f04a07a1c2ad6c.bundle.js, main.6273b0f04a07a1c2ad6c.bundle.map (main) 18.3 kB {3} [initial] [rendered] chunk {1} styles.bfdaa4d8a4eb2d0cb019.bundle.css, styles.bfdaa4d8a4eb2d0cb019.bundle.map, styles.bfdaa4d8a4eb2d0cb019.bundle.map (styles) 154 kB {4} [initial] [rendered] chunk {2} scripts.c5b720a078e5464ec211.bundle.js, scripts.c5b720a078e5464ec211.bundle.map (scripts) 128 kB {4} [initial] [rendered] chunk {3} vendor.07af2467307e17d85438.bundle.js, vendor.07af2467307e17d85438.bundle.map (vendor) 3.96 MB [initial] [rendered] chunk {4} inline.a345391d459797f81820.bundle.js, inline.a345391d459797f81820.bundle.map (inline) 0 bytes [entry] [rendered]

Wait again: such a similar vendor bundle size for prod?

ng build –prod –aotHash: 517e4425ff872bbe3e5b Time: 22856ms chunk {0} main.95eadabace554e3c2b43.bundle.js, main.95eadabace554e3c2b43.bundle.map (main) 130 kB {3} [initial] [rendered] chunk {1} styles.e53a388ae1dd2b7f5434.bundle.css, styles.e53a388ae1dd2b7f5434.bundle.map, styles.e53a388ae1dd2b7f5434.bundle.map (styles) 154 kB {4} [initial] [rendered] chunk {2} scripts.e5c2c90547f3168a7564.bundle.js, scripts.e5c2c90547f3168a7564.bundle.map (scripts) 128 kB {4} [initial] [rendered] chunk {3} vendor.41a6c1f57136df286f14.bundle.js, vendor.41a6c1f57136df286f14.bundle.map (vendor) 2.75 MB [initial] [rendered] chunk {4} inline.97c0403c57a46c6a7920.bundle.js, inline.97c0403c57a46c6a7920.bundle.map (inline) 0 bytes [entry] [rendered]ng build –aotHash: 040cc91df4df5ffc3c3f Time: 11011ms chunk {0} main.bundle.js, main.bundle.map (main) 130 kB {3} [initial] [rendered] chunk {1} styles.bundle.css, styles.bundle.map, styles.bundle.map (styles) 155 kB {4} [initial] [rendered] chunk {2} scripts.bundle.js, scripts.bundle.map (scripts) 128 kB {4} [initial] [rendered] chunk {3} vendor.bundle.js, vendor.bundle.map (vendor) 2.75 MB [initial] [rendered] chunk {4} inline.bundle.js, inline.bundle.map (inline) 0 bytes [entry] [rendered]

So a few questions for deploying my app on prod:

  • Why are the vendor bundles so huge?
  • Is tree shaking properly used by angular-cli?
  • how to improve this bundle size?
  • Are the .map files required?
  • Are the testing features included in bundles? I don?t need them in prod.
  • Generic question: what are the recommanded tools to pack for prod? Maybe angular-cli (using webpack in the background) is not the best suited? Can mwe do MORE?

I searched many discussions on Stack Overflow but I don?t find any generic question.

???

? Answered by Jack Clancy ? ? ?

Some claims that using AOT compilation can reduce the vendor bundle size to 250kb. However, in BlackHoleGalaxy?s example, he uses AOT compilation and is still left with a vendor bundle size of 2.75MB with ng build –prod –aot, 10x larger than the supposed 250kb. This is not out of the norm for angular2 applications, even if you are using v4.0. 2.75MB is still too large for anyone who really cares about performance, especially on a mobile device. There are a few things you can do to help the performance of your application: 1) AOT & Tree Shaking (angular-cli does this out of the box) 2) Using Angular Universal A.K.A. server-side rendering (not in cli) 3) Web Workers (again, not in cli, but a very requested feature)see: https://github.com/angular/angular-cli/issues/23054) Service Workerssee: https://github.com/angular/angular-cli/issues/4006You may not need all of these in a single application, but these are some of the options that are currently present for optimizing Angular performance. I believe/hope Google is aware of the out of the box shortcomings in terms of performance and plans to improve this in the future. Here is a reference that talks more in depth about some of the concepts i mentioned above: https://medium.com/@areai51/the-4-stages-of-perf-tuning-for-your-angular2-app-922ce5c1b294

Angular2 CLI huge vendor bundle: how to improve size for prod?

I have a simple app, initialized by angular-cli. It display some pages relative to 3 routes. I have 3 components. On?

stackoverflow.com

Top ???

? HtmlWebpackPlugin injects relative path files which breaks when loading non-root website paths

? Question got 66+ points, answer got 108+ points ????? 18,739+ viewed

aherriot asked, I am using webpack and the HtmlWebpackPlugin to inject bundled js and css into an html template file.

new HtmlWebpackPlugin({ template: ‘client/index.tpl.html’, inject: ‘body’, filename: ‘index.html’}),

And it produces the following html file.

<!doctype html><html lang=”en”> <head> … <link href=”main-295c5189923694ec44ac.min.css” rel=”stylesheet”> </head> <body> <div id=”app”></div> <script src=”main-295c5189923694ec44ac.min.js”></script> </body></html>

This works fine when visiting the root of the app localhost:3000/, but fails when I try to visit the app from another URL, for example, localhost:3000/items/1 because the bundled files are not injected with an absolute path. When the html file is loaded, it will look for the js file inside the non-exist /items directory because react-router hasn’t loaded yet.How can I get HtmlWebpackPlugin to inject the files with an absolute path, so express will look for them at the root of my /dist directory and not at /dist/items/main-…min.js? Or maybe I can change my express server to work around the issue?

app.use(express.static(__dirname + ‘/../dist’));app.get(‘*’, function response(req, res) { res.sendFile(path.join(__dirname, ‘../dist/index.html’));});

Essentially, I just need to get the line:

<script src=”main…js”></script>

to have a slash at the start of the source.

<script src=”/main…js></script>

???

? Answered by Magnus Sjungare ? ? ?

Try setting the publicPath in your webpack config:

output.publicPath = ‘/’

HtmlWebpackPlugin use the publicPath to prepend the urls of the injects.Another option is to set the base href in the <head> of your html template, to specify the base url of all relative urls in your document.

<base href=”http://localhost:3000/”>

HtmlWebpackPlugin injects relative path files which breaks when loading non-root website paths

I am using webpack and the HtmlWebpackPlugin to inject bundled js and css into an html template file. new?

stackoverflow.com

Top ???

? Webpack how to build production code and how to use it

? Question got 64+ points, answer got 24+ points ????? 89,795+ viewed

Gilson PJ asked, I am very new to webpack, I found that in production build we can able to reduce the size of overall code. Currently webpack builds around 8MB files and main.js around 5MB. How to reduce the size of code in production build? I found a sample webpack configurtion file from internet and I configured for my application and I run npm run buildand its started building and it generated some files in ./dist/ directory.

  1. Still these files are heavy(same as development version)
  2. How to use these files? Currently I am using webpack-dev-server to run the application.

package.json file

{ “name”: “MyAPP”, “version”: “0.1.0”, “description”: “”, “main”: “src/server/server.js”, “repository”: { “type”: “git”, “url”: “” }, “keywords”: [ ], “author”: “Iam”, “license”: “MIT”, “homepage”: “http://example.com”, “scripts”: { “test”: “”, “start”: “babel-node src/server/bin/server”, “build”: “rimraf dist && NODE_ENV=production webpack –config ./webpack.production.config.js –progress –profile –colors” }, “dependencies”: { “scripts” : “”, … }, “devDependencies”: { “scripts” : “”, … }}

webpack.config.js

var path = require(‘path’);var webpack = require(‘webpack’);var HtmlWebpackPlugin = require(‘html-webpack-plugin’);var public_dir = “src/frontend”;var ModernizrWebpackPlugin = require(‘modernizr-webpack-plugin’);module.exports = { devtool: ‘eval-source-map’, entry: [ ‘webpack-hot-middleware/client?reload=true’, path.join(__dirname, public_dir , ‘main.js’) ], output: { path: path.join(__dirname, ‘/dist/’), filename: ‘[name].js’, publicPath: ‘/’ }, plugins: [ plugins ], module: { loaders: [loaders] }};

webpack.production.config.js

var path = require(‘path’);var webpack = require(‘webpack’);var HtmlWebpackPlugin = require(‘html-webpack-plugin’);var public_dir = “src/frontend”;var ModernizrWebpackPlugin = require(‘modernizr-webpack-plugin’);console.log(path.join(__dirname, ‘src/frontend’ , ‘index.html’));module.exports = { devtool: ‘eval-source-map’, entry: [ ‘webpack-hot-middleware/client?reload=true’, path.join(__dirname, ‘src/frontend’ , ‘main.js’) ], output: { path: path.join(__dirname, ‘/dist/’), filename: ‘[name].js’, publicPath: ‘/’ }, plugins: [plugins], resolve: { root: [path.resolve(‘./src/frontend/utils’), path.resolve(‘./src/frontend’)], extensions: [”, ‘.js’, ‘.css’] }, module: { loaders: [loaders] }};

???

? Answered by Gilson PJ ? ? ?

After observing number of viewers to this question I decided to conclude an answer from Vikramaditya and Sandeep.To build the production code the first thing you have to create is production configuration with optimization packages like,

new webpack.optimize.CommonsChunkPlugin(‘common.js’), new webpack.optimize.DedupePlugin(), new webpack.optimize.UglifyJsPlugin(), new webpack.optimize.AggressiveMergingPlugin()

Then in the package.json file you can configure the build procedure with this production configuration

“scripts”: { “build”: “NODE_ENV=production webpack -p –config ./webpack.production.config.js”},

now you have to run the following command to initiate the build

npm run build

As per my production build configuration webpack will build the source to ./dist directory.Now your UI code will be available in ./dist/ directory. Set your server to supply these UI code for the request. and you are done.!

Webpack how to build production code and how to use it

I am very new to webpack, I found that in production build we can able to reduce the size of overall code. Currently?

stackoverflow.com

Top ???

? webpack is not recognized as a internal or external command,operable program or batch file

? Question got 56+ points, answer got 52+ points ????? 61,151+ viewed

yasar asked, I am Learning React.js and i am using windows 8 OS.i have navigate to my root folder

1.Created the package.json file by npm init2. install webpack by npm install -S webpack.now webpack has been downloaded to my modules folder3. install webpack globally by typing npm install webpack -g4. i am also having a webpack.config.js in my root folder which contains the source and ouput directory5. when i type the webpack command i am getting the below error.

webpack is not recognized as a internal or external command,operable program or batch file

???

? Answered by Vlado ? ? ?

I had this issue for a long time too. (webpack installed globally etc. but still not recognized) It turned out that I haven?t specified enviroment variable for npm (where is file webpack.cmd sitting) So I add to my Path variable

c:UsersMeAppDataRoamingnpm

If you are using Powershell, you can type the following command to effectively add to your path :

[Environment]::SetEnvironmentVariable(“Path”, “$env:Path;c:UsersMeAppDataRoamingnpm”, “User”)

IMPORTANT : Don?t forget to close and re-open your powershell window in order to apply this.Hope it helps.

webpack is not recognized as a internal or external command,operable program or batch file

Join Stack Overflow to learn, share knowledge, and build your career. I am Learning React.js and i am using windows 8?

stackoverflow.com

Top ???

? How to create multiple output paths in Webpack config

? Question got 53+ points, answer got 89+ points ????? 36,436+ viewed

spb asked, Does anyone know how to create multiple output paths in a webpack.config.js file? I?m using bootstrap-sass which comes with a few different font files, etc. For webpack to process these i?ve included file-loader which is working correctly, however the files it outputs are being saved to the output path i specified for the rest of my files:

output: { path: __dirname + “/js”, filename: “scripts.min.js” }

I?d like to achieve something where I can maybe look at the extension types for whatever webpack is outputting and for things ending in .woff .eot, etc, have them diverted to a different output path. Is this possible? I did a little googling and came across this *issue on github where a couple of solutions are offered, edit: but it looks as if you need to know the entry point in able to specify an output using the hash method eg:

var entryPointsPathPrefix = ‘./src/javascripts/pages’;var WebpackConfig = { entry : { a: entryPointsPathPrefix + ‘/a.jsx’, b: entryPointsPathPrefix + ‘/b.jsx’, c: entryPointsPathPrefix + ‘/c.jsx’, d: entryPointsPathPrefix + ‘/d.jsx’ }, // send to distribution output: { path: ‘./dist/js’, filename: ‘[name].js’ }}

*https://github.com/webpack/webpack/issues/1189however in my case, as far as the font files are concerned, the input process is kind of abstracted away and all i know is the output. in the case of my other files undergoing transformations, there?s a known point where i?m requiring them in to be then handled by my loaders. if there was a way of finding out where this step was happening, i could then use the hash method to customize output paths, but i don?t know where these files are being required in.

???

? Answered by Yeo ? ? ?

I?m not sure if we have the same problem since webpack only support one output per configuration as of now. I guess you already seen the issue on Github.But I separate the output path by using the multi-compiler. (i.e. separating the configuration object of webpack.config.js).

var config = { // TODO: Add common Configuration module: {},};var fooConfig = Object.assign({}, config, { name: “a”, entry: “./a/app”, output: { path: “./a”, filename: “bundle.js” },});var barConfig = Object.assign({}, config,{ name: “b”, entry: “./b/app”, output: { path: “./b”, filename: “bundle.js” },});// Return Array of Configurationsmodule.exports = [ fooConfig, barConfig, ];

If you have common configuration among them, you could use the extend library or Object.assign in ES6 or {…} spread operator in ES7.

How to create multiple output paths in Webpack config

Does anyone know how to create multiple output paths in a webpack.config.js file? I’m using bootstrap-sass which comes?

stackoverflow.com

Top ???

? How to add fonts to create-react-app based projects?

? Question got 49+ points, answer got 81+ points ????? 18,285+ viewed

Maxim Veksler asked, I?m using https://github.com/facebookincubator/create-react-app and prefer not to ?eject?..It?s not clear where fonts imported via @font-face and loaded locally should go. Namely, I?m loading

@font-face { font-family: ‘Myriad Pro Regular’; font-style: normal; font-weight: normal; src: local(‘Myriad Pro Regular’), url(‘MYRIADPRO-REGULAR.woff’) format(‘woff’);}

Any suggestions? ? EDITIncluding the gist to which Dan referring in his answer

?? Client git:(feature/trivia-game-ui-2) ?? ls -l public/static/fontstotal 1168-rwxr-xr-x@ 1 maximveksler staff 62676 Mar 17 2014 MYRIADPRO-BOLD.woff-rwxr-xr-x@ 1 maximveksler staff 61500 Mar 17 2014 MYRIADPRO-BOLDCOND.woff-rwxr-xr-x@ 1 maximveksler staff 66024 Mar 17 2014 MYRIADPRO-BOLDCONDIT.woff-rwxr-xr-x@ 1 maximveksler staff 66108 Mar 17 2014 MYRIADPRO-BOLDIT.woff-rwxr-xr-x@ 1 maximveksler staff 60044 Mar 17 2014 MYRIADPRO-COND.woff-rwxr-xr-x@ 1 maximveksler staff 64656 Mar 17 2014 MYRIADPRO-CONDIT.woff-rwxr-xr-x@ 1 maximveksler staff 61848 Mar 17 2014 MYRIADPRO-REGULAR.woff-rwxr-xr-x@ 1 maximveksler staff 62448 Mar 17 2014 MYRIADPRO-SEMIBOLD.woff-rwxr-xr-x@ 1 maximveksler staff 66232 Mar 17 2014 MYRIADPRO-SEMIBOLDIT.woff?? Client git:(feature/trivia-game-ui-2) ?? cat src/containers/GameModule.css.GameModule { padding: 15px;}@font-face { font-family: ‘Myriad Pro Regular’; font-style: normal; font-weight: normal; src: local(‘Myriad Pro Regular’), url(‘%PUBLIC_URL%/static/fonts/MYRIADPRO-REGULAR.woff’) format(‘woff’);}@font-face { font-family: ‘Myriad Pro Condensed’; font-style: normal; font-weight: normal; src: local(‘Myriad Pro Condensed’), url(‘%PUBLIC_URL%/static/fonts/MYRIADPRO-COND.woff’) format(‘woff’);}@font-face { font-family: ‘Myriad Pro Semibold Italic’; font-style: normal; font-weight: normal; src: local(‘Myriad Pro Semibold Italic’), url(‘%PUBLIC_URL%/static/fonts/MYRIADPRO-SEMIBOLDIT.woff’) format(‘woff’);}@font-face { font-family: ‘Myriad Pro Semibold’; font-style: normal; font-weight: normal; src: local(‘Myriad Pro Semibold’), url(‘%PUBLIC_URL%/static/fonts/MYRIADPRO-SEMIBOLD.woff’) format(‘woff’);}@font-face { font-family: ‘Myriad Pro Condensed Italic’; font-style: normal; font-weight: normal; src: local(‘Myriad Pro Condensed Italic’), url(‘%PUBLIC_URL%/static/fonts/MYRIADPRO-CONDIT.woff’) format(‘woff’);}@font-face { font-family: ‘Myriad Pro Bold Italic’; font-style: normal; font-weight: normal; src: local(‘Myriad Pro Bold Italic’), url(‘%PUBLIC_URL%/static/fonts/MYRIADPRO-BOLDIT.woff’) format(‘woff’);}@font-face { font-family: ‘Myriad Pro Bold Condensed Italic’; font-style: normal; font-weight: normal; src: local(‘Myriad Pro Bold Condensed Italic’), url(‘%PUBLIC_URL%/static/fonts/MYRIADPRO-BOLDCONDIT.woff’) format(‘woff’);}@font-face { font-family: ‘Myriad Pro Bold Condensed’; font-style: normal; font-weight: normal; src: local(‘Myriad Pro Bold Condensed’), url(‘%PUBLIC_URL%/static/fonts/MYRIADPRO-BOLDCOND.woff’) format(‘woff’);}@font-face { font-family: ‘Myriad Pro Bold’; font-style: normal; font-weight: normal; src: local(‘Myriad Pro Bold’), url(‘%PUBLIC_URL%/static/fonts/MYRIADPRO-BOLD.woff’) format(‘woff’);}

???

? Answered by Dan Abramov ? ? ?

There are two options:

Using Imports

This is the suggested option. It ensures your fonts go through the build pipeline, get hashes during compilation so that browser caching works correctly, and that you get compilation errors if the files are missing.As described in ??Adding Stylesheets on Fonts?, you need to have a CSS file imported from JS. For example, by default src/index.js imports src/index.css:

import ‘./index.css’;

A CSS file like this goes through the build pipeline, and can reference fonts and images. For example, if you put a font in src/fonts/MyFont.woff, your index.css might include this:

@font-face { font-family: ‘MyFont’; src: local(‘MyFont’), url(./fonts/MyFont.woff) format(‘woff’);}

Notice how we??re using a relative path starting with ./. This is a special notation that helps the build pipeline (powered by Webpack) discover this file.Normally this should be enough.

Using public Folder

If for some reason you prefer not to use the build pipeline, and instead do it the ??classic way?, you can use the public folder and put your fonts there.The downside of this approach is that the files don??t get hashes when you compile for production so you??ll have to update their names every time you change them, or browsers will cache the old versions.If you want to do it this way, put the fonts somewhere into the public folder, for example, into public/fonts/MyFont.woff. If you follow this approach, you should put CSS files into public folder as well and not import them from JS because mixing these approaches is going to be very confusing. So, if you still want to do it, you??d have a file like public/index.css. You would have to manually add <link> to this stylesheet from public/index.html:

<link rel=”stylesheet” href=”%PUBLIC_URL%/index.css”>

And inside of it, you would use the regular CSS notation:

@font-face { font-family: ‘MyFont’; src: local(‘MyFont’), url(fonts/MyFont.woff) format(‘woff’);}

Notice how I??m using fonts/MyFont.woff as the path. This is because index.css is in the public folder so it will be served from the public path (usually it??s the server root, but if you deploy to GitHub Pages and set your homepage field to http://myuser.github.io/myproject, it will be served from /myproject). However fonts are also in the public folder, so they will be served from fonts relatively (either http://mywebsite.com/fonts or http://myuser.github.io/myproject/fonts). Therefore we use the relative path.Note that since we??re avoiding the build pipeline in this example, it doesn??t verify that the file actually exists. This is why I don??t recommend this approach. Another problem is that our index.css file doesn??t get minified and doesn??t get a hash. So it??s going to be slower for the end users, and you risk the browsers caching old versions of the file.

Which Way to Use?

Go with the first method (??Using Imports?). I only described the second one since that??s what you attempted to do (judging by your comment), but it has many problems and should only be the last resort when you??re working around some issue.

How to add fonts to create-react-app based projects?

Join Stack Overflow to learn, share knowledge, and build your career. I’m using?

stackoverflow.com

Top ???

? webpack can?t find module if file named jsx

? Question got 47+ points, answer got 114+ points ????? 22,910+ viewed

qiuyuntao asked, As I write webpack.config.js like this

module.exports = { entry: ‘./index.jsx’, output: { filename: ‘bundle.js’ }, module: { loaders: [{ test: /.jsx?$/, exclude: /node_modules/, loader: ‘babel’, query: { presets: [‘es2015’, ‘react’] } }] }};

And in index.jsx I import a react module App

import React from ‘react’;import { render } from ‘react-dom’;import App from ‘./containers/App’;let rootElement = document.getElementById(‘box’)render( <App />, rootElement)

I find if I named module app in App.jsx, then webpack will say in index.jsx can’t find module App, but if I named named module app in App.js, it will find this module and work well.So, I’m confuse about it. In my webpack.config.js, I have writed test: /.jsx?$/ to check file, but why named *.jsx can’t be found?

Image for post

???

? Answered by max ? ? ?

Webpack doesn?t know to resolve .jsx files implicitly. You can specify a file extension in your app (import App from ‘./containers/App.jsx’;). Your current loader test says to use the babel loader when you explicitly import a file with the jsx extension.or, you can include .jsx in the extensions that webpack should resolve without explicit declaration:

module.exports = { entry: ‘./index.jsx’, output: { filename: ‘bundle.js’ }, module: { loaders: [{ test: /.jsx?$/, exclude: /node_modules/, loader: ‘babel’, query: { presets: [‘es2015’, ‘react’] } }] }, resolve: { extensions: [”, ‘.js’, ‘.jsx’], }};

For Webpack 2, leave off the empty extension.

resolve: { extensions: [‘.js’, ‘.jsx’]}

webpack can’t find module if file named jsx

Adding to the above answer, The resolve property is where you have to add all the file types you are using in your?

stackoverflow.com

Top ???

? How to debug Angular with VSCode?

? Question got 46+ points, answer got 75+ points ????? 25,371+ viewed

Asesjix asked, How do I get configure Angular and VSCode so that my breakpoints work?

???

? Answered by Asesjix ? ? ?

  1. Install the Chrome Debugger Extension
  2. Create the launch.json (inside .vscode folder)
  3. Use my launch.json (see below)
  4. Create the tasks.json (inside .vscode folder)
  5. Use my tasks.json (see below)
  6. Press CTRL+SHIFT+B
  7. Press F5

launch.json for angular/cli >= 1.3

{ “version”: “0.2.0”, “configurations”: [ { “name”: “Launch Chrome”, “type”: “chrome”, “request”: “launch”, “url”: “http://localhost:4200/#”, “webRoot”: “${workspaceRoot}” }, { “name”: “Attach Chrome”, “type”: “chrome”, “request”: “attach”, “url”: “http://localhost:4200/#”, “webRoot”: “${workspaceRoot}” }, { “name”: “Launch Chrome (Test)”, “type”: “chrome”, “request”: “launch”, “url”: “http://localhost:9876/debug.html”, “webRoot”: “${workspaceRoot}” }, { “name”: “Launch Chrome (E2E)”, “type”: “node”, “request”: “launch”, “program”: “${workspaceRoot}/node_modules/protractor/bin/protractor”, “protocol”: “inspector”, “args”: [“${workspaceRoot}/protractor.conf.js”] } ]}

tasks.json for angular/cli >= 1.3

{ “version”: “2.0.0”, “tasks”: [ { “identifier”: “ng serve”, “type”: “npm”, “script”: “start”, “problemMatcher”: , “group”: { “kind”: “build”, “isDefault”: true } }, { “identifier”: “ng test”, “type”: “npm”, “script”: “test”, “problemMatcher”: , “group”: { “kind”: “test”, “isDefault”: true } } ] }

Tested with Angular 5 / CLI 1.5.5

  1. Install the Chrome Debugger Extension
  2. Create the launch.json
  3. Use my launch.json (see below)
  4. Start the NG Live Development Server (ng serve)
  5. Press F5

launch.json for angular/cli >= 1.0.0-beta.32

{ “version”: “0.2.0”, “configurations”: [ { “type”: “chrome”, “request”: “launch”, “name”: “Launch Chrome”, “url”: “http://localhost:4200”, “webRoot”: “${workspaceRoot}”, “sourceMaps”: true, “userDataDir”: “${workspaceRoot}/.vscode/chrome”, “runtimeArgs”: [ “–disable-session-crashed-bubble” ] }, { “name”: “Attach Chrome”, “type”: “chrome”, “request”: “attach”, “url”: “http://localhost:4200”, “port”: 9222, “webRoot”: “${workspaceRoot}”, “sourceMaps”: true } ]}

launch.json for angular/cli < 1.0.0-beta.32

{ “version”: “0.2.0”, “configurations”: [ { “name”: “Lunch Chrome”, “type”: “chrome”, “request”: “launch”, “url”: “http://localhost:4200”, “webRoot”: “${workspaceRoot}/src/app”, “sourceMaps”: true, “sourceMapPathOverrides”: { “webpack:///./~/*”: “${workspaceRoot}/node_modules/*”, “webpack:///./src/*”: “${workspaceRoot}/src/*” }, “userDataDir”: “${workspaceRoot}/.vscode/chrome”, “runtimeArgs”: [ “–disable-session-crashed-bubble” ] }, { “name”: “Attach Chrome”, “type”: “chrome”, “request”: “attach”, “url”: “http://localhost:4200”, “port”: 9222, “webRoot”: “${workspaceRoot}/src/app”, “sourceMaps”: true, “sourceMapPathOverrides”: { “webpack:///./~/*”: “${workspaceRoot}/node_modules/*”, “webpack:///./src/*”: “${workspaceRoot}/src/*” } } ]}

Tested with Angular 2.4.8

How to debug Angular with VSCode?

How do I get configure Angular and VSCode so that my breakpoints work?

stackoverflow.com

Top ???

? Path aliases for imports in WebStorm

? Question got 43+ points, answer got 76+ points ????? 10,317+ viewed

Bogdan D asked, I use webpack path aliases for ES6 module loading. E.g. If I define an alias for utils instead of something likeimport Foo from “../../../utils/foo”, I can doimport Foo from “utils/foo”The problem is that once I start using aliases, WebStorm looses track of the import and I’m left with warnings and no auto-completion.Is there a way to instruct WebStorm to use such aliases?

???

? Answered by Jalil ? ? ?

[Deprecated answer. Starting since WS2017.2 Webstorm automatically parses and applies Webpack config (see @anstarovoyt comment)] Yes, there is. In fact, Webstorm can?t automatically parse and apply Webpack config, but you can set up aliases the same way. You just have to mark the parent folder of ?utils? (in your example) as a resource root (right-click, mark directory as / resource root).

Image for post

We just managed to do with the following structure :

/src /A /B /C

We have A B and C folders declared as alias in Webpack. And in Webstorm we marked ?src? as ?Resource Root?. And now we can simply import :

import A/path/to/any/file.js

instead of

import ../../../../../A/path/to/any/file.js

while still having Webstorm correctly parsing and indexing all code, link to files, autocompleting and so on ?

Path aliases for imports in WebStorm

Deprecated answer. Starting since WS2017.2 Webstorm automatically parses and applies Webpack config (see @anstarovoyt?

stackoverflow.com

Top ???

? Webpack-dev-server compiles files but does not refresh or make compiled javascript available to browser

? Question got 42+ points, answer got 46+ points ????? 28,313+ viewed

Chris Schmitz asked, I?m trying to use webpack-dev-server to compile files and start up a dev web server. In my package.json I have the script property set to:

“scripts”: { “dev”: “webpack-dev-server –hot –inline”, }

So the –hot and –inline should enable the webserver and the hot reloading (as I understand it). In my webpack.config.js file I set the entry, output, and devServer settings as well as add a loader to look for changes in .vue files:

module.exports = { entry: ‘./src/index.js’, output: { path: __dirname + ‘/public’, publicPath: ‘/public’, filename: ‘bundle.js’ }, devtool: ‘source-map’, devServer:{ contentBase: __dirname + ‘/public’ }, module:{ loaders:[ { test: /.vue$/, loader: ‘vue’} ] }};

So with this setup, I run npm run dev. The webpack-dev-server starts up, the module loader test works (i.e. when I save any .vue file it causes webpack to recompile), but:

  • The browser never refreshes
  • The compiled javascript that gets stored in memory is never made available to the browser

On that second bullet, I can see this because in the browser window the vue placeholders are never replaced and if I open up the javascript console the Vue instance is never created or made available globally.

Image for post

What am I missing?

???

? Answered by Chris Schmitz ? ? ?

Two things were causing my problems here:

module.exports = { entry: ‘./src/index.js’, output: { // For some reason, the `__dirname` was not evaluating and `/public` was // trying to write files to a `public` folder at the root of my HD. path: __dirname + ‘/public’, // Public path refers to the location from the _browser’s_ perspective, so // `/public’ would be referring to `mydomain.com/public/` instead of just // `mydomain.com`. publicPath: ‘/public’, filename: ‘bundle.js’ }, devtool: ‘source-map’, devServer:{ // `contentBase` specifies what folder to server relative to the // current directory. This technically isn’t false since it’s an absolute // path, but the use of `__dirname` isn’t necessary. contentBase: __dirname + ‘/public’ }, module:{ loaders:[ { test: /.vue$/, loader: ‘vue’} ] }};

Here?s the fixed webpack.config.js:

var path = require(‘path’);module.exports = { entry: [ ‘./src/PlaceMapper/index.js’ ], output:{ filename: ‘bundle.js’, path: path.resolve(__dirname, ‘public/’) }, devtool: ‘source-map’, devServer:{ contentBase: ‘public’ }, module:{ loaders:[ { test: /.vue$/, loader: ‘vue’} ] }};

Webpack-dev-server compiles files but does not refresh or make compiled javascript available to?

I’m trying to use webpack-dev-server to compile files and start up a dev web server. In my package.json I have the?

stackoverflow.com

Top ???

? Webpack loaders vs plugins; what?s the difference?

? Question got 41+ points, answer got 32+ points ????? 6,167+ viewed

Tim Perkins asked, What is the difference between loaders and plugins in webpack? The documentation for plugins just says:

Use plugins to add functionality typically related to bundles in webpack.

I know that babel uses a loader for jsx/es2015 transforms, but it looks like other common tasks (copy-webpack-plugin, for example) use plugins instead.

???

? Answered by helt ? ? ?

Loaders do the pre-processing transformation of virtually any file format when you use sth like require(“my-loader!./my-awesome-module”) in your code. Compared to plugins, they are quite simple as they (a) expose only one single function to webpack and (b) are not able to influence the actual build process.Plugins on the other hand can deeply integrate into webpack because they can register hooks within webpacks build system and access (and modify) the compiler, and how it works, as well as the compilation. Therefore, they are more powerful, but also harder to maintain.

Webpack loaders vs plugins; what’s the difference?

Join Stack Overflow to learn, share knowledge, and build your career. What is the difference between loaders and?

stackoverflow.com

Top ???

? Webpack vs webpack-dev-server vs webpack-dev-middleware vs webpack-hot-middleware vs etc

? Question got 37+ points, answer got 60+ points ????? 8,890+ viewed

Mendes asked, I?m starting working with webpack with a node/express environment developing a ReactJS server side rendered application with react-router. I’m getting very confused about the role of each webpack package for dev and prod (runtime) environments.Here is the summary of my understanding:webpack: Is a package, a tool to join together different pieces of an web application and bundle then in a single .js file (normally bundle.js). The result file is then served in a prod environment to be loaded by the application and contains all necessary components to run the code. Features include shrinking code, minifying, etc.webpack-dev-server: Is a package that offers a server to process the website files. It also builds a single .js file (bundle.js) from client components but serves it in memory. If also has the option (-hot) to monitor all the building files and build a new bundle in memory in case of code changes. The server is served directly in the browser (ex: http:/localhost:8080/webpack-dev-server/whatever). The combination of in memory loading, hot processing and browser serving let the user get the application updated on browser when the code changes, ideal for development environment. If I have doubts about the above text, I’m really not sure about the content below, so please advise me if necessaryA common problem when using webpack-dev-server with node/express is that webpack-dev-server is a server, as is node/express. That makes this environment tricky to run both the client and some node/express code (an API etc.). NOTE: This is what I’ve faced but would be great to understand why does that happens in more details…webpack-dev-middleware: This is a middleware with same functions of webpack-dev-server (inmemory bundling, hot reloading), but in format that can be injected to the server/expressapplication. In that way, you have a sort of server (the webpack-dev-server) insider the node server. Oops: Is this a crazy dream ??? How can this piece solve the dev and prod equation and makes life simplerwebpack-hot-middleware: This… Stuck here… found this piece when looking for webpack-dev-middleware… No idea how to use it. ENDNOTE: Sorry is there is any wrong thinking. I really need help in order to undestand these variants in a complex environment. If conveninent, please add more packages/data that will build the whole scenario.

???

? Answered by riscarrott ? ? ?

webpack

As you?ve described, Webpack is a module bundler, it bundles various module formats primarily so they can be run in a browser. It offers both a CLI and Node API.

webpack-dev-middleware

Webpack Dev Middleware is middleware which can be mounted in an express server to serve the latest compilation of your bundle during development. This uses webpack’s Node API in watch mode and instead of outputting to the file system it outputs to memory.

For comparison, you might use something like express.static instead of this middleware in production.

webpack-dev-server

Webpack Dev Server is itself an express server which uses webpack-dev-middleware to serve the latest bundle and additionally handles hot module replacement (HMR) requests for live module updates in the client.

webpack-hot-middleware

Webpack Hot Middleware is an alternative to webpack-dev-server but instead of starting a server itself it allows you to mount it in an existing / custom express server alongside webpack-dev-middleware.Also…

webpack-hot-server-middleware

Just to confuse things even more, there?s also Webpack Hot Server Middleware which is designed to be used alongside webpack-dev-middleware and webpack-hot-middleware to handle hot module replacement of server rendered apps.

Webpack vs webpack-dev-server vs webpack-dev-middleware vs webpack-hot-middleware vs etc

I’m starting working with webpack with a node/express environment developing a ReactJS server side rendered application?

stackoverflow.com

Top ???

? Error: Cannot resolve module ?style-loader?

? Question got 37+ points, answer got 39+ points ????? 34,767+ viewed

Rahul Dagli asked, I?m using style-loader with webpack and react framework. When I run webpack in terminal i?m getting Module not found: Error: Cannot resolve module ‘style-loader’ in import.js file although i’ve specified the file path correctly.

import ‘../css/style.css’;import React from ‘react’;import ReactDOM from ‘react-dom’;import jQuery from ‘jquery’;import TopicsList from ‘../components/topic-list.jsx’;import Layout from ‘../components/layout.jsx’;

webpack.config.js:

var webpack = require(‘webpack’);var path = require(‘path’);var BUILD_DIR = path.resolve(__dirname, ‘build’);var APP_DIR = path.resolve(__dirname, ‘build’);module.exports = { entry: [ // Set up an ES6-ish environment ‘babel-polyfill’, // Add your application’s scripts below APP_DIR + ‘/import.js’ ], output: { path: BUILD_DIR, filename: ‘bundle.js’ }, module: { loaders: [ { test: /.jsx?$/, loader: ‘babel’, exclude: /node_modules/, query: { plugins: [‘transform-runtime’], presets: [‘es2015’, ‘stage-0’, ‘react’] } }, { test: /.css$/, loader: “style-loader!css-loader” } ], resolve: { extensions: [”, ‘.js’, ‘.jsx’, ‘.css’] } }};

???

? Answered by David Guan ? ? ?

Try run script below:npm install style-loader –saveModify webpack config, add modulesDirectories field in resolve.

resolve: { extensions: [”, ‘.js’, ‘.jsx’, ‘.css’], modulesDirectories: [ ‘node_modules’ ] }

Error: Cannot resolve module ‘style-loader’

I’m using style-loader with webpack and react framework. When I run webpack in terminal i’m getting Module not found?

stackoverflow.com

Top ???

? Angular2: import external js file into component

? Question got 35+ points, answer got 44+ points ????? 73,855+ viewed

Bing Lu asked, I?m going to import this d3gauge.js file into one of my angular2 component, memmon.component.ts file.

import ‘../../../../js/d3gauge.js’;export class MemMonComponent { createMemGauge() { new drawGauge(this.opt); //drawGauge() is a function inside d3gauge.js }}

and in the corresponding template file, add

<script src=”../../../../js/d3gauge.js”></script>

But it doesn?t work, drawGaugecan’t be found. So,

  1. what?re correct steps to import an external js file to angular2?
  2. since I?m using webpack, is it possible to do it in webpack? I refer to this question , the webpack solution there doesn?t work for me as a result of .ensure can’t be resolved.

???

? Answered by Ankit Singh ? ? ?

Ideally you need to have .d.ts file for typings to let Linting work.But It seems that d3gauge doesn’t have one, you can Ask the developers to provide and hope they will listen.Alternatively, you can solve this specific issue by doing this

declare var drawGauge: any;import ‘../../../../js/d3gauge.js’;export class MemMonComponent { createMemGauge() { new drawGauge(this.opt); //drawGauge() is a function inside d3gauge.js }}

If you use it in multiple files, you can create a d3gauage.d.ts file with the content below

declare var drawGauge: any;

and reference it in your boot.ts (bootstrap) file at the top, like this

///<reference path=”../path/to/d3gauage.d.ts”/>

Angular2: import external js file into component

The following approach worked in Angular 5 CLI. For sake of simplicity, I used similar d3gauge.js demo created and?

stackoverflow.com

Top ???

? Correct path for img on React.js

? Question got 34+ points, answer got 29+ points ????? 69,899+ viewed

onedkr asked, I have some problem with my images on my react project. Indeed I always thought that relative path into src attribute was built on the files architectureHere my files architecture:

components file1.jsx file2.jsx file3.jsxconainterimgjs …

However I realized that the path was build on the url. In one of my component (for example into file1.jsx) I have this :

localhost/details/2<img src=”../img/myImage.png” /> -> Workslocalhost/details/2/id<img src=”../img/myImage.png” /> -> doesn’t works, images are not displayed

How is it possible to solve this problem ? I want that in any form of routes handled by react-router, all images can be displayed with the same path.

???

? Answered by prekolna ? ? ?

You?re using a relative url, which is relative to the current url, not the file system. You could resolve this by using absolute urls<img src =”http://localhost:3000/details/img/myImage.png” /> But that’s not great for when you deploy to www.my-domain.bike, or any other site. Better would be to use a url relative to the root directory of the site<img src=”/details/img/myImage.png” />

Correct path for img on React.js

I have some problem with my images on my react project. Indeed I always thought that relative path into src attribute?

stackoverflow.com

Top ???

? How to deploy node that uses Webpack to heroku

? Question got 33+ points, answer got 55+ points ????? 19,542+ viewed

Inanc Gumus asked, I?m using webpack.Also I don?t commit npm_modules folder and public folder, where all generated files are. And I can?t figure out how to build my app (I have webpack build command) after deploy and setup my server (it?s already looking for public folder).It seems me a bad idea to commit before upload. Maybe there are some gentle decisions? Any thoughts?Forked from: How to deploy node that uses Gulp to heroku

???

? Answered by Gaurav Mukherjee ? ? ?

“heroku-postbuild”: “webpack -p –config ./webpack.prod.config.js –progress”

this is better because if you use postinstall, everytime you do npm i the build script get fired

How to deploy node that uses Webpack to heroku

I’m using webpack. Also I don’t commit npm_modules folder and public folder, where all generated files are. And I can’t?

stackoverflow.com

Top ???

? Webpack import returns undefined, depending on the order of imports

? Question got 33+ points, answer got 87+ points ????? 9,081+ viewed

Olegs Jeremejevs asked, I?m using webpack + babel. I have three modules looking like this:

// A.js// some other imports hereconsole.log(‘A’);export default ‘some-const’;// B.jsimport someConst from ‘./A’;console.log(‘B’, someConst);export default ‘something-else’;// main.jsimport someConst from ‘./A’;import somethingElse from ‘./B’;console.log(‘main’, someConst);

When main.js is executed, I see the following:

B undefinedAmain some-const

If I swap the imports in main.js, B becoming the first, I get:

AB some-constmain some-const

How come B.js gets undefined instead of a module in the first version? What’s wrong?

???

? Answered by Olegs Jeremejevs ? ? ?

After almost a full workday of narrowing down the issue (AKA hair-pulling), I?ve finally came to realize that I have a circular dependency.Where it says // some other imports here, A imports another module C, which, in turn, imports B. A gets imported first in main.js, so B ends up being the last link in the “circle”, and Webpack (or any CommonJS-like environment, for that matter, like Node) just short-circuits it by returning A’s module.exports, which is still undefined. Eventually, it becomes equal to some-const, but the synchronous code in B ends up dealing with undefined instead.Eliminating the circular dependency, by moving out the code that C depends on out of B, has resolved the issue. Wish Webpack would somehow warn me about this.Edit: On the last note, as pointed out by @cookie, there’s a plugin for circular dependency detection, if you’d like to avoid hitting this problem [again].

Webpack import returns undefined, depending on the order of imports

After almost a full workday of narrowing down the issue (AKA hair-pulling), I’ve finally came to realize that I have a?

stackoverflow.com

Top ???

? Serving static assets in webpack dev server

? Question got 32+ points, answer got 11+ points ????? 31,428+ viewed

Rem asked, I run webpack-dev-server from the root folder of my project. I have assets folder in /src/assets that is copied by CopyWebPackPlugin:

new CopyWebpackPlugin([ { from: ‘src/assets’, to: ‘assets’ } ])

If I put logo.png inside assets folder then After running webpack-dev-server I can?t access http://localhost/assets/logo.png file, but can access http://localhost/src/assets/logo.png file. However if I run in production mode the situation turns upside down.How to configure webpack server to make http://localhost/assets/logo.png file accessible in development mode?

???

? Answered by dreyescat ? ? ?

You can tell webpack to use a different path when loading from the browser.In the output section of your webpack config file add a publicPath field pointing to your assets folder.webpack.config.js

output: { // your stuff publicPath: ‘/assets/’}

Serving static assets in webpack dev server

Join Stack Overflow to learn, share knowledge, and build your career. I run webpack-dev-server from the root folder of?

stackoverflow.com

Top ???

? Conflict: Multiple assets emit to the same filename

? Question got 31+ points, answer got 37+ points ????? 20,792+ viewed

Andreasrein asked, I?m a webpack rookie who wants to learn all about it. I came across a conflict when running my webpack telling me: ERROR in chunk html [entry] app.js Conflict: Multiple assets emit to the same filename app.jsWhat should I do to avoid the conflict?This is my webpack.config.js:

module.exports = { context: __dirname + “/app”, entry: { ‘javascript’: “./js/app.js”, ‘html’: “./index.html”, }, output: { path: __dirname + “/dist”, filename: “app.js”, }, resolve: { extensions: [‘.js’, ‘.jsx’, ‘.json’] }, module: { loaders: [ { test: /.jsx?$/, exclude: /node_modules/, loaders: [“babel-loader”] }, { test: /.html$/, loader: “file-loader?name=[name].[ext]”, } ] }};

???

? Answered by ickyrr ? ? ?

i?m not quite familiar with your approach so I?ll show you a common way to help you out.First of all, on your output, you are specifying the filename to app.js which makes sense for me that the output will still be app.js. If you want to make it dynamic, then just use “filename”: “[name].js”.The [name] part will make the filename dynamic for you. That’s the purpose of your entry as an object. Each key will be used as a name in replacement of the [name].js.And second, you can use the html-webpack-plugin. You don’t need to include it as a test.

Conflict: Multiple assets emit to the same filename

I’m a webpack rookie who wants to learn all about it. I came across a conflict when running my webpack telling me?

stackoverflow.com

Top ???

? Is it possible to write webpack config in typescript?

? Question got 30+ points, answer got 36+ points ????? 4,963+ viewed

starcorn asked, I saw, when searching, that there are typings for webpack. So it seems I can write webpack.config.js in typescript? But how can I do that?

Image for post

???

? Answered by Shlomi Assaf ? ? ?

You can use TS as your config file (webpack.config.ts)There is a clear clue for that, see Source CodeThe ** interpret** module used there is a list of extension files and their loaders.In the highlighted code webpack generates an array of all possible extension for the default files.For example, give webpack.config you will get an array with

  • webpack.config.ts
  • webpack.config.js
  • ?? and so on

For this to work you need to install one of the packages that support loading your extension.For example, TS has some node packages that enable you to require(?something.ts?) and the package will do the work.The interpret package states that one of these packages is required

ts-node, typescript-node, typescript-register, typescript-require

So npm/yarn ts-node then just put a webpack.config.ts file and it will just work!EDIT: Webpack documentation now has dedicated section on configuration languages which includes TypeScript, CoffeeScript and Babel & JSX

Is it possible to write webpack config in typescript?

I saw, when searching, that there are typings for webpack. So it seems I can write webpack.config.js in typescript? But?

stackoverflow.com

Top ???

? How to minify ES6 code using Webpack?

? Question got 28+ points, answer got 49+ points ????? 7,900+ viewed

H. Pauwelyn asked, I?m using webpack and want to deploy my site. If I minify and bundle my JavaScript code, I?ve got this error:

Parse error: Unexpected token: name (Button)

Here is my not bundled code:

‘use strict’;export class Button { // <– Error happens on this line constructor(translate, rotate, text, textscale = 1) { this.position = translate; this.rotation = rotate; this.text = text; this.textscale = textscale; }}

Note in bundled code the keyword export is removed. In development, there are no errors thrown. Here you could find my configuration file of WebPack:

var webpack = require(‘webpack’);var PROD = true;module.exports = { entry: “./js/entry.js”, output: { path: __dirname, filename: PROD ? ‘bundle.min.js’ : ‘bundle.js’ }, module: { loaders: [ { test: /.css$/, loader: “style-loader!css-loader” } ] }, plugins: PROD ? [ new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false }, output: { comments: false, }, }) ] : };

If I change PROD to false, I’ve no error, if true I’ve got error from above. My question is can I enable ES6 in Webpack?

???

? Answered by user3432422 ? ? ?

Not sure if you?re still looking for an answer to this, but now you can include the beta version of uglifyjs-webpack-plugin as a webpack plugin and it?ll use uglify-es which can minify ES6 code.

npm install uglifyjs-webpack-plugin

and then in your webpack.config.js:

const Uglify = require(“uglifyjs-webpack-plugin”);module.exports = { entry: …, output: …, plugins: [ new Uglify() ]};

How to minify ES6 code using Webpack?

I’m using webpack and want to deploy my site. If I minify and bundle my JavaScript code, I’ve got this error: Parse?

stackoverflow.com

Top ???

? What is the value of using Webpack with HTTP/2

? Question got 23+ points, answer got 14+ points ????? 2,934+ viewed

battmanz asked, I?m starting a new project and I?m trying to be forward thinking about it. I?ve used Browserify in the past. For my new project I would like to use either Webpack, Rollup, or SystemJS. Webpack looks by far to be the most mature with tons of awesome features.I?m concerned, though, that Webpack is going to be irrelevant in a year or two with the adoption of HTTP/2. So I?m wondering, what value does Webpack offer for a site being served over HTTP/2? I?m not looking for an opinion, but a factual explanation of the benefits of using Webpack with HTTP/2. If there are no benefits, or very little benefits, that would also help me with my decision.

???

? Answered by rluta ? ? ?

TL;DR In HTTP/1.1, you had to make as few requests as possible to get performance; in HTTP/2 you have minimal performance impact per request but can still hit resource constraints and dependency management that will require a bundling tool such as webpack.Long version:Webpack (or any other bundler) can still provide value in an HTTP/2 world because while HTTP/2 allows multiplexed, asynchronous, simultaneous queries from the client to the server, it doesn?t mean that the actual server you?re connecting to has unlimited capacity to process them or will even allow them.In the SETTINGS frame sent when you connect, most servers will restrict the number of concurrent streams to a reasonable value such as 100. This means you can not issue more than 100 concurrent requests, which is an issue if you have for example a large unbundled React app with hundreds of js files.Furthermore, in many cases, you have transitive dependencies between javascript files and if you don?t bundle all the dependencies, you?ll need many request round-trips as the browser will only discover dependencies when it receives the previous responses, negating HTTP/2 benefits. (Alternatively the server may be able to push automatically the dependencies but this creates a whole other set of issues).For these reasons, it makes sense to use webpack to package a number of homogeneous bundles to make sure your maximum concurrent requests stay below the server limits while keeping your bundle granular enough to leverage efficient browser caching.

What is the value of using Webpack with HTTP/2

TL;DR In HTTP/1.1, you had to make as few requests as possible to get performance; in HTTP/2 you have minimal?

stackoverflow.com

Top ???

? How to use images in css with Webpack

? Question got 23+ points, answer got 32+ points ????? 17,416+ viewed

user3737841 asked, I am making a React w/ Webpack setup and am struggling to do what seems like should be a simple task. I want webpack to include images, and minimize them like I with gulp but I can?t figure it out. I just want to be able to link an image in my css like so:

/* ./src/img/background.jpg */body { background: url(‘./img/background.jpg’); }

I have all of my css/js/img folders inside a src folder. Webpack outputs to a dist folder, but I can?t figure out how to get images there.Here is my webpack setup:

var path = require(‘path’); var webpack = require(‘webpack’); var HtmlWebpackPlugin = require(‘html-webpack-plugin’); module.exports = { devtool: ‘cheap-eval-source-map’, entry: [ ‘webpack-dev-server/client?http://localhost:8080’, ‘webpack/hot/dev-server’, ‘./src/index.js’ ], output: { path: path.join(__dirname, ‘dist’), // publicPath: ‘./dist’, filename: ‘bundle.js’ }, plugins: [ new webpack.HotModuleReplacementPlugin(), new HtmlWebpackPlugin({ template: ‘./src/index.html’ }) ], module: { loaders: [{ exclude: /node_modules/, test: /.js?$/, loader: ‘babel’ }, { test: /.scss$/, loader: ‘style!css!sass’ }, { test: /.(png|jpg)$/, loader: ‘file-loader’ }] }, devServer: { historyApiFallback: true, contentBase: ‘./dist’, hot: true }};

???

? Answered by WitVault ? ? ?

I was stuck with similar issue and found that you can use url-loader to resolve “url()” statements in your CSS as any other require or import statements.To install it:npm install url-loader –save-dev It will install the loader that can convert resolved paths as BASE64 strings.In your webpack config file use url-loader in loaders

{ test: /.(png|jpg)$/, loader: ‘url-loader’}

Also make sure that you are specifying your public path correctly and path of images you are trying to load.

How to use images in css with Webpack

I am making a React w/ Webpack setup and am struggling to do what seems like should be a simple task. I want webpack to?

stackoverflow.com

Top ???

? Avoiding relative paths in Angular CLI

? Question got 22+ points, answer got 32+ points ????? 10,733+ viewed

Pratik Kelwalkar asked, I?m using the latest Angular CLI, and I?ve created a custom components folder which is a collection of all components.For example, TextInputComponent has a TextInputConfiguration class which is placed inside src/components/configurations.ts, and in src/app/home/addnewuser/add.user.component.ts where I use it there is:

import {TextInputConfiguration} from “../../../components/configurations”;

This is fine but as my app gets larger and deeper the ../ increases, how do I handle this?Previously, for SystemJS, I would configure the path through system.config.js as below:

System.config({.. map : {‘ng_custom_widgets’:’components’ }, packages : {‘ng_custom_widgets’:{main:’configurations.ts’, defaultExtension: ‘ts’},)};

How do I produce the same for webpack using Angular CLI?

???

? Answered by jonrsharpe ? ? ?

Per this comment, you can add your application source via paths in tsconfig.json:

{ “compilerOptions”: { …, “baseUrl”: “.”, “paths”: { …, “@app/*”: [“app/*”], “@components/*”: [“components/*”] } }}

Then you can import absolutely from app/ or components/ instead of relative to the current file:

import {TextInputConfiguration} from “@components/configurations”;

Note: baseUrl must be specified if paths is.See also

  • https://www.typescriptlang.org/docs/handbook/module-resolution.html#path-mapping

Avoiding relative paths in Angular CLI

Thanks to jonrsharpe’s answer for pointing me in right direction. Although, after adding the paths, as defined in?

stackoverflow.com

Top ???

10

No Responses

Write a response