GithubHelp home page GithubHelp logo

webpack-demos's Introduction

This repo is a collection of simple demos of Webpack.

These demos are purposely written in a simple and clear style. You will find no difficulty in following them to learn the powerful tool.

How to use

First, install Webpack and webpack-dev-server globally.

$ npm i -g webpack webpack-dev-server

Then, clone the repo.

$ git clone https://github.com/ruanyf/webpack-demos.git

Install the dependencies.

$ cd webpack-demos
$ npm install

Now, play with the source files under the repo's demo* directories.

$ cd demo01
$ npm run dev

If the above command doesn't open your browser automatically, you have to visit http://127.0.0.1:8080 by yourself.

Foreword: What is Webpack

Webpack is a front-end tool to build JavaScript module scripts for browsers.

It can be used similar to Browserify, and do much more.

$ browserify main.js > bundle.js
# be equivalent to
$ webpack main.js bundle.js

Webpack needs a configuration file called webpack.config.js which is just a CommonJS module.

// webpack.config.js
module.exports = {
  entry: './main.js',
  output: {
    filename: 'bundle.js'
  }
};

After having webpack.config.js, you can invoke Webpack without any arguments.

$ webpack

Some command-line options you should know.

  • webpack – building for development
  • webpack -p – building for production (minification)
  • webpack --watch – for continuous incremental building
  • webpack -d – including source maps
  • webpack --colors – making building output pretty

You could customize scripts field in your package.json file as following.

// package.json
{
  // ...
  "scripts": {
    "dev": "webpack-dev-server --devtool eval --progress --colors",
    "deploy": "NODE_ENV=production webpack -p"
  },
  // ...
}

Index

  1. Entry file
  2. Multiple entry files
  3. Babel-loader
  4. CSS-loader
  5. Image loader
  6. CSS Module
  7. UglifyJs Plugin
  8. HTML Webpack Plugin and Open Browser Webpack Plugin
  9. Environment flags
  10. Code splitting
  11. Code splitting with bundle-loader
  12. Common chunk
  13. Vendor chunk
  14. Exposing Global Variables
  15. React router

Demo01: Entry file (source)

Entry file is a file which Webpack reads to build bundle.js.

For example, main.js is an entry file.

// main.js
document.write('<h1>Hello World</h1>');

index.html

<html>
  <body>
    <script type="text/javascript" src="bundle.js"></script>
  </body>
</html>

Webpack follows webpack.config.js to build bundle.js.

// webpack.config.js
module.exports = {
  entry: './main.js',
  output: {
    filename: 'bundle.js'
  }
};

Launch the server, visit http://127.0.0.1:8080 .

$ cd demo01
$ npm run dev

Demo02: Multiple entry files (source)

Multiple entry files are allowed. It is useful for a multi-page app which has different entry file for each page.

// main1.js
document.write('<h1>Hello World</h1>');

// main2.js
document.write('<h2>Hello Webpack</h2>');

index.html

<html>
  <body>
    <script src="bundle1.js"></script>
    <script src="bundle2.js"></script>
  </body>
</html>

webpack.config.js

module.exports = {
  entry: {
    bundle1: './main1.js',
    bundle2: './main2.js'
  },
  output: {
    filename: '[name].js'
  }
};

Demo03: Babel-loader (source)

Loaders are preprocessors which transform a resource file of your app (more info) before Webpack's building process.

For example, Babel-loader can transform JSX/ES6 file into normal JS files,after which Webpack will begin to build these JS files. Webpack's official doc has a complete list of loaders.

main.jsx is a JSX file.

// main.jsx
const React = require('react');
const ReactDOM = require('react-dom');

ReactDOM.render(
  <h1>Hello, world!</h1>,
  document.querySelector('#wrapper')
);

index.html

<html>
  <body>
    <div id="wrapper"></div>
    <script src="bundle.js"></script>
  </body>
</html>

webpack.config.js

module.exports = {
  entry: './main.jsx',
  output: {
    filename: 'bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['es2015', 'react']
          }
        }
      }
    ]
  }
};

The above snippet uses babel-loader which needs Babel's preset plugins babel-preset-es2015 and babel-preset-react to transpile ES6 and React.

Demo04: CSS-loader (source)

Webpack allows you to include CSS in JS file, then preprocessed CSS file with CSS-loader.

main.js

require('./app.css');

app.css

body {
  background-color: blue;
}

index.html

<html>
  <head>
    <script type="text/javascript" src="bundle.js"></script>
  </head>
  <body>
    <h1>Hello World</h1>
  </body>
</html>

webpack.config.js

module.exports = {
  entry: './main.js',
  output: {
    filename: 'bundle.js'
  },
  module: {
    rules:[
      {
        test: /\.css$/,
        use: [ 'style-loader', 'css-loader' ]
      },
    ]
  }
};

Attention, you have to use two loaders to transform CSS file. First is CSS-loader to read CSS file, and another one is Style-loader to insert <style> tag into HTML page.

Then, launch the server.

$ cd demo04
$ npm run dev

Actually, Webpack inserts an internal style sheet into index.html.

<head>
  <script type="text/javascript" src="bundle.js"></script>
  <style type="text/css">
    body {
      background-color: blue;
    }
  </style>
</head>

Demo05: Image loader (source)

Webpack could also include images in JS files.

main.js

var img1 = document.createElement("img");
img1.src = require("./small.png");
document.body.appendChild(img1);

var img2 = document.createElement("img");
img2.src = require("./big.png");
document.body.appendChild(img2);

index.html

<html>
  <body>
    <script type="text/javascript" src="bundle.js"></script>
  </body>
</html>

webpack.config.js

module.exports = {
  entry: './main.js',
  output: {
    filename: 'bundle.js'
  },
  module: {
    rules:[
      {
        test: /\.(png|jpg)$/,
        use: [
          {
            loader: 'url-loader',
            options: {
              limit: 8192
            }
          }
        ]
      }
    ]
  }
};

url-loader transforms image files into <img> tag. If the image size is smaller than 8192 bytes, it will be transformed into Data URL; otherwise, it will be transformed into normal URL.

After launching the server, small.png and big.png have the following URLs.

<img src="data:image/png;base64,iVBOR...uQmCC">
<img src="4853ca667a2b8b8844eb2693ac1b2578.png">

Demo06: CSS Module (source)

css-loader?modules (the query parameter modules) enables the CSS Module which gives a local scoped CSS to your JS module's CSS. You can switch it off with :global(selector) (more info).

index.html

<html>
<body>
  <h1 class="h1">Hello World</h1>
  <h2 class="h2">Hello Webpack</h2>
  <div id="example"></div>
  <script src="./bundle.js"></script>
</body>
</html>

app.css

/* local scope */
.h1 {
  color:red;
}

/* global scope */
:global(.h2) {
  color: blue;
}

main.jsx

var React = require('react');
var ReactDOM = require('react-dom');
var style = require('./app.css');

ReactDOM.render(
  <div>
    <h1 className={style.h1}>Hello World</h1>
    <h2 className="h2">Hello Webpack</h2>
  </div>,
  document.getElementById('example')
);

webpack.config.js

module.exports = {
  entry: './main.jsx',
  output: {
    filename: 'bundle.js'
  },
  module: {
    rules:[
      {
        test: /\.js[x]?$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['es2015', 'react']
          }
        }
      },
      {
        test: /\.css$/,
        use: [
          {
            loader: 'style-loader'
          },
          {
             loader: 'css-loader',
             options: {
               modules: true
             }
          }
        ]
      }
    ]
  }
};

Launch the server.

$ cd demo06
$ npm run dev

Visiting http://127.0.0.1:8080 , you'll find that only second h1 is red, because its CSS is local scoped, and both h2 is blue, because its CSS is global scoped.

Demo07: UglifyJs Plugin (source)

Webpack has a plugin system to expand its functions. For example, UglifyJs Plugin will minify output(bundle.js) JS codes.

main.js

var longVariableName = 'Hello';
longVariableName += ' World';
document.write('<h1>' + longVariableName + '</h1>');

index.html

<html>
<body>
  <script src="bundle.js"></script>
</body>
</html>

webpack.config.js

var webpack = require('webpack');
var UglifyJsPlugin = require('uglifyjs-webpack-plugin');

module.exports = {
  entry: './main.js',
  output: {
    filename: 'bundle.js'
  },
  plugins: [
    new UglifyJsPlugin()
  ]
};

After launching the server, main.js will be minified into following.

var o="Hello";o+=" World",document.write("<h1>"+o+"</h1>")

Demo08: HTML Webpack Plugin and Open Browser Webpack Plugin (source)

This demo shows you how to load 3rd-party plugins.

html-webpack-plugin could create index.html for you, and open-browser-webpack-plugin could open a new browser tab when Webpack loads.

main.js

document.write('<h1>Hello World</h1>');

webpack.config.js

var HtmlwebpackPlugin = require('html-webpack-plugin');
var OpenBrowserPlugin = require('open-browser-webpack-plugin');

module.exports = {
  entry: './main.js',
  output: {
    filename: 'bundle.js'
  },
  plugins: [
    new HtmlwebpackPlugin({
      title: 'Webpack-demos',
      filename: 'index.html'
    }),
    new OpenBrowserPlugin({
      url: 'http://localhost:8080'
    })
  ]
};

Launch the server.

$ cd demo08
$ npm run dev

Now you don't need to write index.html by hand and don't have to open browser by yourself. Webpack did all these things for you.

Demo09: Environment flags (source)

You can enable some codes only in development environment with environment flags.

main.js

document.write('<h1>Hello World</h1>');

if (__DEV__) {
  document.write(new Date());
}

index.html

<html>
<body>
  <script src="bundle.js"></script>
</body>
</html>

webpack.config.js

var webpack = require('webpack');

var devFlagPlugin = new webpack.DefinePlugin({
  __DEV__: JSON.stringify(JSON.parse(process.env.DEBUG || 'false'))
});

module.exports = {
  entry: './main.js',
  output: {
    filename: 'bundle.js'
  },
  plugins: [devFlagPlugin]
};

Now pass environment variable into webpack. Opening demo09/package.json, you should find scripts field as following.

// package.json
{
  // ...
  "scripts": {
    "dev": "cross-env DEBUG=true webpack-dev-server --open",
  },
  // ...
}

Launch the server.

$ cd demo09
$ npm run dev

Demo10: Code splitting (source)

For big web apps, it’s not efficient to put all code into a single file. Webpack allows you to split a large JS file into several chunks. Especially, if some blocks of code are only required under some circumstances, these chunks could be loaded on demand.

Webpack uses require.ensure to define a split point (official document).

// main.js
require.ensure(['./a'], function (require) {
  var content = require('./a');
  document.open();
  document.write('<h1>' + content + '</h1>');
  document.close();
});

require.ensure tells Webpack that ./a.js should be separated from bundle.js and built into a single chunk file.

// a.js
module.exports = 'Hello World';

Now Webpack takes care of the dependencies, output files and runtime stuff. You don't have to put any redundancy into your index.html and webpack.config.js.

<html>
  <body>
    <script src="bundle.js"></script>
  </body>
</html>

webpack.config.js

module.exports = {
  entry: './main.js',
  output: {
    filename: 'bundle.js'
  }
};

Launch the server.

$ cd demo10
$ npm run dev

On the surface, you won't feel any differences. However, Webpack actually builds main.js and a.js into different chunks(bundle.js and 0.bundle.js), and loads 0.bundle.js from bundle.js when on demand.

Demo11: Code splitting with bundle-loader (source)

Another way of code splitting is using bundle-loader.

// main.js

// Now a.js is requested, it will be bundled into another file
var load = require('bundle-loader!./a.js');

// To wait until a.js is available (and get the exports)
//  you need to async wait for it.
load(function(file) {
  document.open();
  document.write('<h1>' + file + '</h1>');
  document.close();
});

require('bundle-loader!./a.js') tells Webpack to load a.js from another chunk.

Now Webpack will build main.js into bundle.js, and a.js into 0.bundle.js.

Demo12: Common chunk (source)

When multi scripts have common chunks, you can extract the common part into a separate file with CommonsChunkPlugin, which is useful for browser caching and saving bandwidth.

// main1.jsx
var React = require('react');
var ReactDOM = require('react-dom');

ReactDOM.render(
  <h1>Hello World</h1>,
  document.getElementById('a')
);

// main2.jsx
var React = require('react');
var ReactDOM = require('react-dom');

ReactDOM.render(
  <h2>Hello Webpack</h2>,
  document.getElementById('b')
);

index.html

<html>
  <body>
    <div id="a"></div>
    <div id="b"></div>
    <script src="commons.js"></script>
    <script src="bundle1.js"></script>
    <script src="bundle2.js"></script>
  </body>
</html>

The above commons.js is the common chunk of main1.jsx and main2.jsx. As you can imagine, commons.js includes react and react-dom.

webpack.config.js

var webpack = require('webpack');

module.exports = {
  entry: {
    bundle1: './main1.jsx',
    bundle2: './main2.jsx'
  },
  output: {
    filename: '[name].js'
  },
  module: {
    rules:[
      {
        test: /\.js[x]?$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['es2015', 'react']
          }
        }
      },
    ]
  },
  plugins: [
    new webpack.optimize.CommonsChunkPlugin({
      name: "commons",
      // (the commons chunk name)

      filename: "commons.js",
      // (the filename of the commons chunk)
    })
  ]
}

Demo13: Vendor chunk (source)

You can also extract the vendor libraries from a script into a separate file with CommonsChunkPlugin.

main.js

var $ = require('jquery');
$('h1').text('Hello World');

index.html

<html>
  <body>
    <h1></h1>
    <script src="vendor.js"></script>
    <script src="bundle.js"></script>
  </body>
</html>

webpack.config.js

var webpack = require('webpack');

module.exports = {
  entry: {
    app: './main.js',
    vendor: ['jquery'],
  },
  output: {
    filename: 'bundle.js'
  },
  plugins: [
    new webpack.optimize.CommonsChunkPlugin({
      name: 'vendor',
      filename: 'vendor.js'
    })
  ]
};

In above codes, entry.vendor: ['jquery'] tells Webpack that jquery should be included in the common chunk vendor.js.

If you want a module available as a global variable in every module, such as making $ and jQuery available in every module without writing require("jquery"). You should use ProvidePlugin (Official doc) which automatically loads modules instead of having to import or require them everywhere.

// main.js
$('h1').text('Hello World');


// webpack.config.js
var webpack = require('webpack');

module.exports = {
  entry: {
    app: './main.js'
  },
  output: {
    filename: 'bundle.js'
  },
  plugins: [
    new webpack.ProvidePlugin({
      $: 'jquery',
      jQuery: 'jquery'
    })
  ]
};

Of course, in this case, you should load jquery.js globally by yourself.

Demo14: Exposing global variables (source)

If you want to use some global variables, and don't want to include them in the Webpack bundle, you can enable externals field in webpack.config.js (official document).

For example, we have a data.js.

// data.js
var data = 'Hello World';

index.html

<html>
  <body>
    <script src="data.js"></script>
    <script src="bundle.js"></script>
  </body>
</html>

Attention, Webpack will only build bundle.js, but not data.js.

We can expose data as a global variable.

// webpack.config.js
module.exports = {
  entry: './main.jsx',
  output: {
    filename: 'bundle.js'
  },
  module: {
    rules:[
      {
        test: /\.js[x]?$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['es2015', 'react']
          }
        }
      },
    ]
  },
  externals: {
    // require('data') is external and available
    //  on the global var data
    'data': 'data'
  }
};

Now, you require data as a module variable in your script. but it actually is a global variable.

// main.jsx
var data = require('data');
var React = require('react');
var ReactDOM = require('react-dom');

ReactDOM.render(
  <h1>{data}</h1>,
  document.body
);

You could also put react and react-dom into externals, which will greatly decrease the building time and building size of bundle.js.

Demo15: React router (source)

This demo uses webpack to build React-router's official example.

Let's imagine a little app with a dashboard, inbox, and calendar.

+---------------------------------------------------------+
| +---------+ +-------+ +--------+                        |
| |Dashboard| | Inbox | |Calendar|      Logged in as Jane |
| +---------+ +-------+ +--------+                        |
+---------------------------------------------------------+
|                                                         |
|                        Dashboard                        |
|                                                         |
|                                                         |
|   +---------------------+    +----------------------+   |
|   |                     |    |                      |   |
|   | +              +    |    +--------->            |   |
|   | |              |    |    |                      |   |
|   | |   +          |    |    +------------->        |   |
|   | |   |    +     |    |    |                      |   |
|   | |   |    |     |    |    |                      |   |
|   +-+---+----+-----+----+    +----------------------+   |
|                                                         |
+---------------------------------------------------------+

webpack.config.js

module.exports = {
  entry: './index.js',
  output: {
    filename: 'bundle.js'
  },
  module: {
    rules: [
      {
        test: /\.css$/,
        use: [ 'style-loader', 'css-loader' ]
      },
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: ['es2015', 'react']
          }
        }
      },
    ]
  }
};

index.js

import React from 'react';
import { render } from 'react-dom';
import { BrowserRouter, Switch, Route, Link } from 'react-router-dom';

import './app.css';

class App extends React.Component {
  render() {
    return (
      <div>
        <header>
          <ul>
            <li><Link to="/app">Dashboard</Link></li>
            <li><Link to="/inbox">Inbox</Link></li>
            <li><Link to="/calendar">Calendar</Link></li>
          </ul>
          Logged in as Jane
        </header>
        <main>
          <Switch>
            <Route exact path="/" component={Dashboard}/>
            <Route path="/app" component={Dashboard}/>
            <Route path="/inbox" component={Inbox}/>
            <Route path="/calendar" component={Calendar}/>
            <Route path="*" component={Dashboard}/>
          </Switch>
        </main>
      </div>
    );
  }
};

class Dashboard extends React.Component {
  render() {
    return (
      <div>
        <p>Dashboard</p>
      </div>
    );
  }
};

class Inbox extends React.Component {
  render() {
    return (
      <div>
        <p>Inbox</p>
      </div>
    );
  }
};

class Calendar extends React.Component {
  render() {
    return (
      <div>
        <p>Calendar</p>
      </div>
    );
  }
};

render((
  <BrowserRouter>
    <Route path="/" component={App} />
  </BrowserRouter>
), document.querySelector('#app'));

index.html

<html>
  <body>
    <div id="app"></div>
    <script src="/bundle.js"></script>
  </body>
</htmL>

Launch the server.

$ cd demo15
$ npm run dev

Useful links

License

MIT

webpack-demos's People

Contributors

anxsec avatar deemoding avatar godky avatar imnot2 avatar jackqiang123 avatar jason-cooke avatar jayechong avatar jigsawye avatar kohei-takata avatar luoxiaobatman avatar mofelee avatar muyepeikon avatar nicoder avatar qingmingsang avatar qiuyuntao avatar ruanyf avatar sizappaaigwat avatar tron-robin avatar xiaohp avatar yehonal avatar zhuolikevin avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

webpack-demos's Issues

demo08 error

when i run demo08 , it reports errors.

demo08 git:(master) ✗ webpack-dev-server
http://localhost:8080/webpack-dev-server/
webpack result is served from /
content is served from /home/yanjie/Public/github/webpack-demos/demo08
Hash: fc2be4484e3356d26c56
Version: webpack 1.13.0
Time: 76ms
Asset Size Chunks Chunk Names
bundle.js 1.43 kB 0 [emitted] main
index.html 52 bytes [emitted]
chunk {0} bundle.js (main) 40 bytes [rendered]
[0] ./main.js 40 bytes {0} [built]

ERROR in Path must be a string. Received undefined
webpack: bundle is now VALID.

使用demo过程的一些问题

感谢您提供这么好的例子,不过不知道是否是版本更新的问题,在学习的过程中发现了这些问题。
1.demo08 不用书写html源文件,在实际的演示过程中,并没有出现预期的结果(包含hello wold的index.html)。仅显示服务器[webpack-dev-server]的js文件列表页
2.demo09 我使用的是window环境,
但是命令行输入DEBUG=true webpack-dev-server,提示没有这个命令debug[cmder无法识别这个命令]。需要再另外安装别的软件么?

热替换Demo15会页面刷新

替换Demo15,自己测试发现是会刷新页面的,是搞错了吗?
我用的是第二种方式 webpack-dev-server
修改后页面是有更新,但是会刷新

Demo08跑不起来

具体报错为

ERROR in   TypeError: Cannot read property 'request' of undefined
  
  - ExternalModuleFactoryPlugin.js:37 handleExternals
    [webpack-demos]/[.1.14.0@webpack]/lib/ExternalModuleFactoryPlugin.js:37:33
  
  - ExternalModuleFactoryPlugin.js:46 next
    [webpack-demos]/[.1.14.0@webpack]/lib/ExternalModuleFactoryPlugin.js:46:8
  
  - ExternalModuleFactoryPlugin.js:59 handleExternals
    [webpack-demos]/[.1.14.0@webpack]/lib/ExternalModuleFactoryPlugin.js:59:7
  
  - ExternalModuleFactoryPlugin.js:79 ExternalModuleFactoryPlugin.<anonymous>
    [webpack-demos]/[.1.14.0@webpack]/lib/ExternalModuleFactoryPlugin.js:79:5
  
  - NormalModuleFactory.js:233 
    [lib]/[webpack]/lib/NormalModuleFactory.js:233:3
  
  - Tapable.js:196 NormalModuleFactory.applyPluginsAsyncWaterfall
    [lib]/[webpack]/[tapable]/lib/Tapable.js:196:70
  
  - NormalModuleFactory.js:217 NormalModuleFactory.create
    [lib]/[webpack]/lib/NormalModuleFactory.js:217:8
  
  - Compilation.js:377 Compilation._addModuleChain
    [lib]/[webpack]/lib/Compilation.js:377:17
  
  - Compilation.js:455 Compilation.addEntry
    [lib]/[webpack]/lib/Compilation.js:455:8
  
  - SingleEntryPlugin.js:22 SingleEntryPlugin.<anonymous>
    [webpack-demos]/[.1.14.0@webpack]/lib/SingleEntryPlugin.js:22:15
  
  - Tapable.js:229 Compiler.applyPluginsParallel
    [lib]/[webpack]/[tapable]/lib/Tapable.js:229:14
  
  - Compiler.js:469 
    [lib]/[webpack]/lib/Compiler.js:469:8
  
  - Tapable.js:131 Compiler.applyPluginsAsyncSeries
    [lib]/[webpack]/[tapable]/lib/Tapable.js:131:46
  
  - Compiler.js:462 Compiler.compile
    [lib]/[webpack]/lib/Compiler.js:462:7
  
  - Compiler.js:266 Compiler.runAsChild
    [lib]/[webpack]/lib/Compiler.js:266:7
  
  - compiler.js:70 
    [webpack-demos]/[.2.28.0@html-webpack-plugin]/lib/compiler.js:70:19

nodejs版本是6.9.2

README.md demo03 "another way" loader should be babel-loader

Original:

module: {
  loaders: [
    {
      test: /\.jsx?$/,
      exclude: /node_modules/,
      loader: 'babel',
      query: {
        presets: ['es2015', 'react']
      }
    }
  ]
}

fix:

module: {
  loaders: [
    {
      test: /\.jsx?$/,
      exclude: /node_modules/,
      loader: 'babel-loader',
      query: {
        presets: ['es2015', 'react']
      }
    }
  ]
}

用到babel-loader的报错了。。

➜ demo03 git:(master) webpack-dev-server
http://localhost:8080/webpack-dev-server/
webpack result is served from /
content is served from /Users/noughtchen/mydev/ReactJs/ohehe/webpack-demos/demo03
Hash: 396f0bfb9d565b6f60f0
Version: webpack 1.14.0
Time: 663ms

ERROR in ./main.jsx
Module build failed: Error: Plugin 19 specified in "/Users/noughtchen/mydev/ReactJs/ohehe/webpack-demos/node_modules/babel-preset-es2015/index.js" provided an invalid property of "__esModule"
at Plugin.init (/Users/noughtchen/mydev/ReactJs/ohehe/webpack-demos/node_modules/babel-core/lib/transformation/plugin.js:124:13)
at Function.normalisePlugin (/Users/noughtchen/mydev/ReactJs/ohehe/webpack-demos/node_modules/babel-core/lib/transformation/file/options/option-manager.js:155:12)
at /Users/noughtchen/mydev/ReactJs/ohehe/webpack-demos/node_modules/babel-core/lib/transformation/file/options/option-manager.js:184:30
at Array.map (native)
at Function.normalisePlugins (/Users/noughtchen/mydev/ReactJs/ohehe/webpack-demos/node_modules/babel-core/lib/transformation/file/options/option-manager.js:161:20)
at OptionManager.mergeOptions (/Users/noughtchen/mydev/ReactJs/ohehe/webpack-demos/node_modules/babel-core/lib/transformation/file/options/option-manager.js:254:36)
at OptionManager.mergePresets (/Users/noughtchen/mydev/ReactJs/ohehe/webpack-demos/node_modules/babel-core/lib/transformation/file/options/option-manager.js:308:16)
at OptionManager.mergeOptions (/Users/noughtchen/mydev/ReactJs/ohehe/webpack-demos/node_modules/babel-core/lib/transformation/file/options/option-manager.js:270:12)
at OptionManager.init (/Users/noughtchen/mydev/ReactJs/ohehe/webpack-demos/node_modules/babel-core/lib/transformation/file/options/option-manager.js:396:10)
at File.initOptions (/Users/noughtchen/mydev/ReactJs/ohehe/webpack-demos/node_modules/babel-core/lib/transformation/file/index.js:191:75)
webpack: bundle is now VALID.

Could we rename the "demoX" folders to declarative names?

Hi, I appreciate what you've done so far, I love it. But i think it will be great for newbie if we can rename the "demoX" folder to declarative names so that they can have a very quick look.

Let me know if you think it makes sense.

demo15热刷新没有效果

按说明用webpack-dev-server跑起来后,改动js没有热刷新,而是直接刷新了。
chrome的控制台输出:[HMR] Waiting for update signal from WDS...

DEMO09,run error.

I run the following command in Win7 cmd:

env DEBUG=true webpack-dev-server

and the cmd show: 'env' is not a internal or external command ...

大多demo跑不起来

阮老师您好,这个问题什么原因呢,报错缺少某个包。是不是需要更新某些东西,非常感谢啦

Cleaner demos without React?

It would be nice to have simple demos dedicated to single purpose each, without React or any other external resources that do not serve the main purpose of the individual demo.

The package [email protected] does not satisfy its siblings' peerDependencies requirements!

An error occured when run npm install

oldkobe:webpack-demos oldkobe$ npm i 
npm ERR! Darwin 15.2.0
npm ERR! argv "node" "/usr/local/bin/npm" "i"
npm ERR! node v0.10.36
npm ERR! npm  v2.14.4
npm ERR! code EPEERINVALID

npm ERR! peerinvalid The package [email protected] does not satisfy its siblings' peerDependencies requirements!
npm ERR! peerinvalid Peer [email protected] wants history@^1.17.0

npm ERR! Please include the following file with any support request:
npm ERR!     /Users/oldkobe/Desktop/webpack-demos/npm-debug.log

hope it can be fixed as soon as possible!

webpack-dev-server not found!

I follow the readme and i also find the package webpack-dev-server in node_modules.
but the bash show me webpack-dev-server not found

README.md 里这个 git地址是不是需要更新了

git clone [email protected]:ruanyf/webpack-demos.git
Cloning into 'webpack-demos'...
Warning: Permanently added the RSA host key for IP address '192.30.253.112' to the list of known hosts.
Permission denied (public key).
fatal: Could not read from remote repository.

Please make sure you have the correct access rights
and the repository exists.

demo3 有问题

运行webpack后,提示我这个....
`ERROR in Cannot find module '../modules/web.dom.iterable'

说好的汉语呢

为么子全是英文,高大上的赶脚,就是看起来不是很方便啦,哈哈,同意的点个赞

阮老师,webpack-dev-server可以设置成手机也能访问么?

使用webpack-dev-server 打开的是 localhost:8080
我的内网地址是'10.0.0.21', 我直接替换成'10.0.0.21:8080'是不能访问的,
那有没有什么机制可以更改呢?如果改成这个手机和电脑在同一局域网,就可以手机调试了

demo06 打包失败

执行命令webpack时,报错。

ERROR in ./main.jsx
Module build failed: Error: Plugin 19 specified in "/Users/biggie.ding/codes/personal/webpack-demos/node_modules/babel-preset-es2015/index.js" provided an invalid property of "__esModule"

demo13里面关于第三方插件不合并的问题

你好!我试了您的demo13!但是有些疑问!
1.您在outfile里面最后生成了两个js文件。一个vendor.js里面包含了jquery的!,但是在mian.js里面又require了jquery,所以的话,bundle。js里面也包含了jquery!这样不会重复了吗?
2.我去掉了demo13里面main.js里面的 var $= rquire("jquery") 但是报了一个错就是$ 未定义

请问可以帮我解答一下吗?谢谢

热加载没有效果

系统:win10
工具:Git Bash
浏览器: chrome

我按照要求测试了热加载效果,当我改变文字的时候,浏览器页面没有得到预期的改变

webpack 抽离共用文件?

需求:
在gulp或者grunt打包中:
1、共用库抽离:zepto、util.js、module.js(自行封装的业务模块等);当然还有common.css(实际开发中使用less编写)。一般我会抽离成库文件base.js、模块工具类util.js和common.css。
2、页面文件:page.js和page.css。

问题:

声明:使用vue2+vuex+vue-router2+ES6+LESS(SASS)+webpack2

1、我使用了vue-router2的路由懒加载。所以会对每一个页面生成一个chunk.js。(里面会包含当前页面css和js代码。当然还有import导入的工具类和模块代码,虽然这不是我想要的。)

2、JS:我目前已经使用CommonsChunkPlugin实现了第三方插件的抽离(主要是采用在app.js入口文件中导入解决)。但自行封装的ajax业务逻辑和util等,即通过具体页面import moduleobj from module 使用的模块代码在每一个chunk.js中有存在。可能有人说设置option.children=true;这样会把太多非共用封装的模块代码都打包到共用文件去了。说了这么多,我只是感觉webpack没法想gulp或者grunt那样对每一个文件包括文件的内容进行精细化的控制。

3、CSS:目前我共用的common样式采用less编写。通过在入口页面import可以实现。但问题是iconfont图标库必须通过gulp转移到build目录。直接common.less中去引用iconfont.css会报错!同时页面自身的css目前都在chunk.js中。有人可能使用ExtractTextPlugin进行抽离。但还是不够精细。我想应该每个页面抽离初一个样式文件page.css。然后一个公用的common.css。

一句话:就是怎么抽离共用的文件(共用插件库、业务模块库、页面逻辑、共用样式、页面样式)

当然很可能也是我对webpack还不熟悉,没法精细化控制。

react-hot-reload

项目生成的bundle.js 在哪 还是只是一个临时文件

Demo8 webpack 配置错误

var HtmlwebpackPlugin = require('html-webpack-plugin');
var OpenBrowserPlugin = require('open-browser-webpack-plugin');

module.exports = {
  entry: './main.js',
  output: {
    filename: 'bundle.js'
  },
  plugins: [
    new HtmlwebpackPlugin({
      title: 'Webpack-demos',
      filename: 'index.html'
    }),
    new OpenBrowserPlugin({
      url: 'http://localhost:8080'
    })
  ]
};

使用HtmlwebpackPlugin,需要配置文件名,否则会报错

ERROR in Path must be a string. Received undefined

关于工程中对less文件的处理

你好,请教一下假如我的工程目录是
丨__build
丨__src
丨_____css
丨________a.less
丨________b.less

src是开发目录,在src/css下有很多 less文件,通常需要先将这多个less文件分别利用autoprefixer添加兼容前缀编译成css文件到 src/css 目录下,因为src开发目录是需要上传到gitlab的文件。最终,需要将之前生成的 src/css/*.css 文件 压缩合并成一个all.css文件到build/css目录下,这个all.css是线上的文件。请问这些操作我该如何利用webpack配置完成?

同理,其实还有src/images 中的图片也是要先压缩到 src/images/下,再输出到 build/images/目录下。相当于是得输出到多个目录下,请问如何解决?谢谢。

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.