WebPack
Webpack
Getting Started
Motivation
- Module system styles
-
CommonJS: synchronous require
-
AMD: asynchronous require
-
ES6: modules
- Transferring
Modules should be executed on the client. so they must be transferred from the server to the browser.
-
1 request per module
-
all modules in one request
What’s webpack
What’s webpack
Webpack is module bunder, This means webpack takes modules with dependecies and emit static assets representing those modules .
Dependencies can be written in CommonJS or in AMD
// webpack is a module bundler
// This means webpack takes modules with dependencies
// and emits static assets representing those modules.
// dependencies can be written in CommonJs
var commonjs = require("./commonjs");
// or in AMD
define(["amd-module", "../file"], function(amdModule, file) {
// while previous constructs are sync
// this is async
require(["big-module/big/file"], function(big) {
// for async dependencies webpack splits
// your application into multiple "chunks".
// This part of your application is
// loaded on demand (Code Splitting)
var stuff = require("../my/stuff");
// "../my/stuff" is also loaded on demand
// because it's in the callback function
// of the AMD require
});
});
require("coffee!./cup.coffee");
// "Loaders" can be used to preprocess files.
// They can be prefixed in the require call
// or configured in the configuration.
require("./cup");
// This does the same when you add ".coffee" to the extensions
// and configure the "coffee" loader for /\.coffee$/
function loadTemplate(name) {
return require("./templates/" + name + ".jade");
// many expressions are supported in require calls
// a clever parser extracts information and concludes
// that everything in "./templates" that matches
// /\.jade$/ should be included in the bundle, as it
// can be required.
}
// ... and you can combine everything
function loadTemplateAsync(name, callback) {
require(["bundle?lazy!./templates/" + name + ".jade"],
function(templateBundle) {
templateBundle(callback);
});
}
- How is webpack different ?
- Code Splitting
webpack has two types of dependencies in its dependency tree: sync and async. Async dependencies act as split points and form a new chunk. After the chunk tree is optimized, a file is emitted for each chunk.
- Loaders
webpack can only process JavaScript natively, but loaders are used to transform other resources into JavaScript. By doing so, every resource forms a module.
- Clerver parsing
webpack has a clever parser that can process nearly every 3rd party library.
- Plugin system
webpack features a rich plugin system. Most internal features are based on this plugin system. This allows you to customize webpack for your needs and distribute common plugins as open source.
Installation
npm install webpack -g
npm install webpack-dev-server –save-dev
Usage
CLI
webpack <entry> <output>
- entry
Pass a file or request strng, Your can pass multiple entries(every entry is loaded on startup)
Node.js
var webpack = require("webpack");
// returns a Compiler instance
var compiler = webpack({
// configuration
});
compiler.run(function(err, stats) {
// ...
});
// or
compiler.watch({ // watch options:
aggregateTimeout: 300, // wait so long for more changes
poll: true // use polling instead of native watchers
// pass a number to set the polling interval
}, function(err, stats) {
// ...
});
Configuration
If your use the CLI will read a file webpack.config.js(or the file passed by the –config option) ,If you use the node.js youd need to pass the configruation object as parameter.
- context
The Base directory(absolute path!) for resolving the entry option
- entry
The entry point for the bundle
If your pass a string: The string is resolved to a module which is loaded upon startup.
If you pass an array: All modules are loaded upon startup. The last one es exported.
- output
output.*
- Module
Using loaders
-
Installation
npm install ***-loader –save
npm install ***-loader –save-dev
-
Loader
{ module: { loaders: [ { test: /\.jade$/, loader: "jade" }, // => "jade" loader is used for ".jade" files { test: /\.css$/, loader: "style!css" }, // => "style" and "css" loader is used for ".css" files // Alternative syntax: { test: /\.css$/, loaders: ["style", "css"] }, ] } }
- Babel-loader can transform JSX/ES6 f ile into JS file . Official doc has a complete list of loaders
Dev tools
The webpack-dev-server is a little node.js Express server. which use the webpack-dev-middleware to serve a webpack bundle. It also has a littile runtime which is connected to the server via Socket.IO. The server emits information
about the compilation sate to the client which reacts to thoes events.
webpack-dev-server --content-base public/
http://localhost:8080/assets/bundle.js
Tutorial AND Exmaple
Books
React webpack cookbook(done)
- 加载CSS
加载 CSS 需要 css-loader 和 style-loader,他们做两件不同的事情,css-loader会遍历 CSS 文件,然后找到 url() 表达式然后处理他们,style-loader 会把原来的 CSS 代码插入页面中的一个 style 标签中。
- CSS-loader
The query parameter modules enables the CSS Modules spec. (css-loader?modules)
This enables Local scoped CSS by default. (You can switch it off with :global(…) or :global for selectors and/or rules.)
Local scope ``` :local(.className) { background: red; } :local .className { color: green; } :local(.className .subClass) { color: green; } :local .className .subClass :global(.global-class-name) { color: blue; } is transformed to ._23_aKvs-b8bW2Vg3fwHozO { background: red; } ._23_aKvs-b8bW2Vg3fwHozO { color: green; } ._23_aKvs-b8bW2Vg3fwHozO ._13LGdX8RMStbBE9w-t0gZ1 { color: green; } ._23_aKvs-b8bW2Vg3fwHozO ._13LGdX8RMStbBE9w-t0gZ1 .global-class-name { color: blue; }
React-dom
In the browser
var React = require('react');
var ReactDOM = require('react-dom');
class MyComponent extends React.Component {
render() {
return <div>Hello World</div>;
}
}
ReactDOM.render(<MyComponent />, node);
On the server
var React = require('react');
var ReactDOMServer = require('react-dom/server');
class MyComponent extends React.Component {
render() {
return <div>Hello World</div>;
}
}
ReactDOMServer.renderToString(<MyComponent />);
API
react-dom
findDOMNode
render
unmountComponentAtNode
react-dom/server
renderToString
renderToStaticMarkup
Notes
- webpack.config.js
We need two webpack.config.js files one for devleop, another for production.
- 3nd-parth by npm install, no longer need bowser
npm install jquery –save-dev