webpack教程不识别jsx的<标记,有谁遇到过

&&一、全面理解webpack1、什么是&webpack?webpack是近期最火的一款模块加载器兼打包工具,它能把各种资源,例如JS(含JSX)、coffee、样式(含less/sass)、图片等都作为模块来使用和处理,它能有Grunt或Gulp所有基本功能。webpack的官网是&http://webpack.github.io/&,文档地址是&http://webpack.github.io/docs/,官网对webpack的定义是MODULE BUNDLER,他的目的就是把有依赖关系的各种文件打包成一系列的静态资源。 请看下图:2、webpack&的优势其优势主要可以归类为如下几个:webpack&是以&commonJS&的形式来书写脚本滴,但对&AMD/CMD&的支持也很全面,方便旧项目进行代码迁移。支持很多模块加载器的调用,可以使模块加载器灵活定制,比如babel-loader加载器,该加载器能使我们使用ES6的语法来编写代码;less-loader加载器,可以将less编译成css文件;开发便捷,能替代部分&grunt/gulp&的工作,比如打包、压缩混淆、图片转base64等。可以通过配置打包成多个文件,有效的利用浏览器的缓存功能提升性能。3、wepback它的目标是是什么?webpack它能将依赖的模块转化成可以代表这些包的静态文件将依赖的模块分片化,并且按需加载解决大型项目初始化加载慢的问题每一个静态文件都可以看成一个模块可以整合第三方库能够在大型项目中运用可以自定义切割模块的方式4、webpack较之其他类似工具有什么不同?有同步和异步两种不同的加载方式Loader,加载器可以将其他资源整合到JS文件中,通过这种方式,可以讲所有的源文件形成一个模块优秀的语法分析能力,支持&CommonJs&AMD&规范有丰富的开源插件库,可以根据自己的需求自定义webpack的配置5、webpack为什么要将所有资源放在一个文件里面?我们知道,对于浏览器来说,加载的资源越少,响应的速度也就越快,所以有时候我们为了优化浏览器的性能,会尽可能的将资源合并到一个主文件app.js里面。但是这导致的很大的缺点:当你的项目十分庞大的时候,不同的页面不能做到按需加载,而是将所有的资源一并加载,耗费时间长,性能降低。会导致依赖库之间关系的混乱,特别是大型项目时,会变得难以维护和跟踪。比如:哪些文件是需要A模块加载完后才能执行的?哪些页面会受到多个样式表同时影响的?&等许多问题。而webpack可以很好的解决以上缺点,因为它是一个十分聪明的模块打包系统,当你正确配置后,它会比你想象中的更强大,更优秀。二、开启wbpack之旅安装步骤如下:1、生成package.json文件;先装好node和npm,因为webpack是一个基于node的项目。然后首先我们需要在根目录下生成package.json文件,需要进入项目文件内根目录下执行如下命令:npm&init如上通过一问一答的方式后会在根目录下生成package.json文件,如下所示:2&.&通过全局安装webpack执行命令如下:npm&install&-g&webpack&如下所示:在c盘下会生成node_modules文件夹中会包含webpack,此时此刻我们可以使用webpack命令了;在常规项目中把webpack依赖加入到package.jsonnpm&init&npm&install&webpack&--save更详尽的安装方法个可以参考webpack安装3.&配置webpack每个目录下都必须有一个webpack.config.js,它的作用就好比Gulpfile.js、或者&Gruntfile.js,就是一个项目配置,告诉webpack需要做什么。首先先贴上一个比较完整的webpack.config.js的代码,再详细介绍:?1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980var webpack = require('webpack');var HtmlWebpackPlugin = require('html-webpack-plugin');var TransferWebpackPlugin = require('transfer-webpack-plugin');&module.exports = {&&&&devtool: 'source-map',&&&&&&&&&&&&entry: {&&&&&&&&page1: "./src/index.js",&&&&&&&&&&&&},&&&&&&&&output: {&&&&&&&&path: "dist/js/page",&&&&&&&&filename: "[name].bundle.js",&&&&&&&&publicPath: "/dist/"&&& &&&&},&&&&module: {&&&&&&&&&&&&&&&&loaders: [&&&&&&&&&&&&{ test: /\.css$/, loader: 'style-loader!css-loader' },&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&&{ test: /\.scss$/, loader: 'style!css!sass?sourceMap'},&&&&&&&&&&&&{ test: /\.less$/, loader: 'style!css!less?sourceMap'},&&&&&&&&&&&&{ test: /\.js$/, loader: 'babel!jsx' },&&&&&&&&&&&&&{ test: /\.jsx$/, loader: "jsx-loader?harmony" },&&&&&&&&&&&&{ test: /\.(png|jpg|jpeg|gif)$/, loader: 'url-loader?limit=8192'},&&&&&&&&&&&&&{ test: /\.jade$/, loader: "jade-loader" },&&&&&&&&&&&&{ test: /\.coffee$/, loader: 'coffee-loader' }&&&&&&&&]&&&&},&&&&&&&&plugins: [&&&&&&&&new monsChunkPlugin('common.js'),&&&&&&&&new webpack.optimize.UglifyJsPlugin({&&&&&&&&&&compressor: {&&&&&&&&&&&&warnings: false,&&&&&&&&&&},&&&&&&&&&&except: ['$super', '$', 'exports', 'require']&&& &&&&&&&&}),&&&&&&&&new webpack.DefinePlugin({&&&&&&&&&&&&&__DEV__: JSON.stringify(JSON.parse(process.env.BUILD_DEV || 'true')),&&&&&&&&&&&&&__PRERELEASE__: JSON.stringify(JSON.parse(process.env.BUILD_PRERELEASE || 'false'))&&&&&&&&}),&&&&&&&&new webpack.ProvidePlugin({&&&&&&&&&&&&&&&&&&&&&&&&&&$: "jquery",&&&&&&&&&&&&&jQuery: "jquery",&&&&&&&&&&&&&"window.jQuery": "jquery"&&&&&&&&&}),&&&&&&&&new webpack.NoErrorsPlugin(), &&&&&&&&new TransferWebpackPlugin([ &&&&&&&&&&{from: 'www'}&&&&&&&&], path.resolve(__dirname,"src")),&&&&&&&&new HtmlwebpackPlugin({&&&&&&&&&&&title: 'Hello World app',&&&&&&&&&&&filename: 'assets/admin.html'&&&&&&&&})&&&&],&&&&&&&&resolve: {&&&&&&&&root: 'E:/github/flux-example/src', &&&&&&&&extensions: ['', '.js', '.json', '.scss'], &&&&&&&&alias: {&&&&&&&&&&&&&&&&&&&&&&&&&&& &&&&&&&&&&&&AppStore : 'js/stores/AppStores.js',&&&&&&&&&&&&ActionType : 'js/actions/ActionType.js',&&&&&&&&&&&&AppAction : 'js/actions/AppAction.js'&&&&&&&&},&&&&&&&&modulesDirectories: [&&&&&&&&&&&&&'node_modules',&&&&&&&&&&&&&'bower_components',&&&&&&&&&&&&&'lib',&&&&&&&&&&&&&'src'&&&&&&&&]&&&&}&&&&&};&plugins中包含很多的内置插件和外部插件,它们都有各自的功能,用来处理相关的文件,这里只是罗列了部分,具体用法请看webpack入门和实战(二)全面理解plugins和loader。就像我在前面提到的,webpack.config.js的写法和在Node里的写法相同,我们主要看的就是文件中的module.exports里面的内容entry&是指入口文件的配置项,它是一个数组的原因是webpack允许多个入口点。output是指输出文件的配置项path&-&表示输出文件的路径filename&-&表示输出文件的文件名plugins&顾名思义,使用插件可以给webpack添加更多的功能,使webpack更加的灵活和强大,webpack有两种类型的插件:webpack内置的插件//&首先要先安装webpack模块var webpack = require("webpack");
module.exports = { & &new webpack.optimize.UglifyJsPlugin({
& & &compressor: {
& & & &warnings: false,
};&&webpack外置插件//npm install component-webpack-plugin 先要在安装该模版var ComponentPlugin = require("component-webpack-plugin");
module.exports = {
& &plugins: [ & & & &new ComponentPlugin()
}更多的插件以及插件的用法,大家可以到webpack的插件上查看。module&配置处理文件的选项loaders&一个含有wepback中能处理不同文件的加载器的数组test&用来匹配相对应文件的正则表达式loaders&告诉webpack要利用哪种加载器来处理test所匹配的文件loaders&的安装方法        $&npm&install&xxx-loader&--save-devresolve:其它解决方案配置;&resolve.root,绝对路径,&查找module的话从这里开始查找(可选)resolve.modulesDirectories,取相对路径,所以比起&root&,所以会多&parse&很多路径。查找module(可选)resolve.extensions,自动扩展文件后缀名,意味着我们require模块可以省略不写后缀名resolve.alias,模块别名定义,方便后续直接引用别名,无须多写长长的地址三、利用webpack实现在页面上合理使用打包过后的js文件和图片示例如下:webpack_test目录结构如下:最终完成版的目录结构为:&index.html代码如下:&!DOCTYPE html&
&html lang="en"&
&meta charset="UTF-8"&
&title&demo1&/title&
&div id="content"&&/div&
&img src="./build/img/demo.png"&
&script src="./build/js/index.js"&&/script&
&/html&index.js代码如下:require('./index.css');index.css代码如下:#content{
& &width:121
& &height:140
& &background-color:
}demo.png自己随便找一张即可;根据webpack.config.js的配置情况,操作步骤如下:全局安装webpack,npm install webpack -g进入到webpack_test目录下,初始化生成package.json文件,npm init需要安装的loader有css-loader、style-loader、url-loader,webpack, npm install css-loader style-loader url-loader webpack--save-dev执行webpack,生成打包过后的build/js/index.js,build/img/demo.png在index.html中引入即可效果如下:&源码地址为:http://download.csdn.net/detail/wdlhao/9612173,有需要的同学可以自行下载练习;&四、理解webpack支持commonJS和AMD/CMD两种模块机制进行打包&1.AMD/CMD模式:& & &AMD&规范在这里:/amdjs/amdjs-api/wiki/AMD,CMD&规范在这里:/seajs/seajs/issues/242AMD(Asynchronous&Module&Definition)&是&RequireJS&在推广过程中对模块定义的规范化产出。(即RequireJS模块规范)RequireJS是一个工具库,主要用于客户端的模块管理。它可以让客户端的代码分成一个个模块,实现异步或动态加载,从而提高代码的性能和可维护性。它的模块管理遵守AMD规范(Asynchronous&Module&Definition)。RequireJS的基本思想是,通过define方法,将代码定义为模块;通过require方法,实现代码的模块加载。首先,将require.js嵌入网页,然后就能在网页中进行模块化编程了。&script&data-main="scripts/main"&src="scripts/require.js"&&/script&上面代码的data-main属性不可省略,用于指定主代码所在的脚本文件,在上例中为scripts子目录下的main.js文件。用户自定义的代码就放在这个main.js文件中。CMD(Common&Module&Definition&)是&SeaJS&在推广过程中对模块定义的规范化产出。(即SeaJS模块规范)SeaJS是一个遵循CMD规范的JavaScript模块加载框架,可以实现JavaScript的模块化开发及加载机制。CommonJS&Modules/2.0&规范,是&BravoJS&在推广过程中对模块定义的规范化产出。CommonJS&API定义很多普通应用程序(主要指非浏览器的应用)使用的API,从而填补了这个空白。它的终极目标是提供一个类似Python,Ruby和Java标准库。这样的话,开发者可以使用CommonJS&API编写应用程序,然后这些应用可以运行在不同的JavaScript解释器和不同的主机环境中。在兼容CommonJS的系统中,你可以实用JavaScript程序开发:服务器端JavaScript应用程序命令行工具图形界面应用程序混合应用程序(如,Titanium或Adobe&AIR)还有不少??这些规范的目的都是为了&JavaScript&的模块化开发,特别是在浏览器端的。目前这些规范的实现都能达成浏览器端模块化开发的目的。&2、AMD/CMD模式区别2.1从官方推荐的写法上面得出:CMD ----- 依赖就近Js代码
//CMD define(function(require,exports,module){
& var a = require('./a');
& a.doSomthing();
});AMD ----- 依赖前置Js代码
//AMD define(['./a','./b'],function(a,b){
//...... a.doSomthing();
//...... b.doSomthing();
})当然AMD也支持CMD的写法。2.2、执行顺序上:&CMD是延迟执行,推崇的是as&lazy&as&possibleAMD是提前执行,requireJS从2.0开始可以延迟执行2.3、api设计角度:&CMD的API推崇职责单一,没有全局的require&AMD的API默认是一个当多个用:比如require有全局的和局部的jing(csjing68) 
 文章为作者独立观点,不代表大不六文章网立场
的最新文章
为什么需要URL规范化1、网站URL和结构已经成为网站搜索引擎友好的最大基础性问题,网站URL 和结构问题 场景有这样一个场景,一个邮件提醒的windows服务,获取所有开启邮件提醒的用户,循环获取这些用户的邮件, 为什么需要URL规范化1、网站URL和结构已经成为网站搜索引擎友好的最大基础性问题,网站URL 和结构问题 Sencha Ext JS号称是目前世界上最先进和最强大的、支持多平台多设备的JavaScript应用程序 一、预备知识:
1、LVM是什么?LVM是 Logical Volume Manager(逻辑卷管理 在每个MongoDB(版本 3.2.9) Instance中,都有一个本地数据库(local),用于存储
在MongoDB(版本 3.2.9)中,分片集群(sharded cluster)是一种水平扩展数据库系统原文地址:http://blog.codefx.org/design/architecture/junit-
一.SQLite的介绍 1.为什么要存储数据?
1.1 手机数据大多都是从网络加载的,不存储
使用vue.js原文介绍:Vue.js是一个构建数据驱动的web界面库。Vue.js的目标是通过尽可能 前言AntPathMatcher是什么?主要用来解决什么问题?背景:在做uri匹配规则发现这个类,根据源码
一、全面理解webpack1、什么是 webpack?webpack是近期最火的一款模块加载器兼打包工具   iOS系统库中定义了软件开发中常用的加解密算法,接口为C语言形式。具体包括了以下几个大类:1 #inc以往做nuget包我们一般要么用命令行,要么用nuget的图形化界面去做,但是一些操作比较麻烦.比如引入命名空间,引入第三方nuget包。这些在.NET Core项目里却很简单,只需要使用命令行dotnet pack  Execl功能非常强大,内置的很多函数或公式可以大大提高对数据的加工处理能力。那么在web中有没有类似的表单的数据检验对一个程序来讲非常重要,因为对于客户端的数据不能完全信任,常规的检验类型有:参数为空,根据不同 F# 项目在之前的几篇文章介绍的代码都在交互窗口(fsi.exe)里运行,但平常开发的软件程序可能含有大类 Redis的数据结构:1,字符串:键名-string用法:1 127.0.0.1:6379> get us12年,12个经验教训。今天我发现了一个奇怪的网站:https://www.livecoding.tv。一点进去它的主页就有一个直播多年以来,黑程序员一直是一项广大人民群众喜闻乐见的娱乐活动,我们不仅黑程序员,程序员也喜欢自黑,如此一来,大家好像都觉得黑程序员是一项天经地义的事情了,然而事实上,的确是的。csjing68帮助你了解互联网的那些趣事。热门文章最新文章csjing68帮助你了解互联网的那些趣事。应该是最好懂的 Webpack 教程 - 掘金
阅读 7764收藏 83原文链接:项目模板库地址:/ruanyf/react-babel-webpack-boilerplate —— 由
分享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
$ npm i -g webpack webpack-dev-server
Then, clone the repo and install the dependencies.
$ git clone :ruanyf/webpack-demos.git
$ cd webpack-demos
$ npm install
Now, play with the source files under the repo's demo* directories.
$ cd demo01
$ webpack-dev-server
Visit http://127.0.0.1:8080 with your browser.
Foreword: What is Webpack
Webpack is a front-end build systems like Grunt and Gulp.
It can be used as a module bundler similar to Browserify, and do .
$ browserify main.js & bundle.js
# be equivalent to
$ webpack main.js bundle.js
Its configuration file is webpack.config.js.
// webpack.config.js
module.exports = {
entry: './main.js',
filename: 'bundle.js'
After having webpack.config.js, you can invoke Webpack without any arguments.
Some command-line options you should know.
webpack – for building once for development
webpack -p – for building once for production (minification)
webpack --watch – for continuous incremental build
webpack -d – to include source maps
webpack --colors – for making things pretty
To produce a production ready application, you could write 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&
Demo01: Entry file ()
Entry file is a file which Webpack will read to build bundle.js.
For example, main.js is an entry file.
// main.js
document.write('&h1&Hello World&/h1&');
index.html
&script type=&text/javascript& src=&bundle.js&&&/script&
Webpack follows webpack.config.js to build bundle.js.
// webpack.config.js
module.exports = {
entry: './main.js',
filename: 'bundle.js'
Launch the server, visit http://127.0.0.1:8080 .
$ webpack-dev-server
Demo02: Multiple entry files ()
Multiple entry files are allowed. It is useful for a multi-page app.
// main1.js
document.write('&h1&Hello World&/h1&');
// main2.js
document.write('&h2&Hello Webpack&/h2&');
index.html
&script src=&bundle1.js&&&/script&
&script src=&bundle2.js&&&/script&
webpack.config.js
module.exports = {
bundle1: './main1.js',
bundle2: './main2.js'
filename: '[name].js'
Demo03: Babel-loader ()
Loaders are preprocessors which transform a resource file of your app (). For example,
can transform JSX/ES6 file into JS file. Official doc has a complete list of .
main.jsx is a JSX file.
const React = require('react');
const ReactDOM = require('react-dom');
ReactDOM.render(
&h1&Hello, world!&/h1&,
document.querySelector('#wrapper')
index.html
&div id=&wrapper&&&/div&
&script src=&bundle.js&&&/script&
webpack.config.js
module.exports = {
entry: './main.jsx',
filename: 'bundle.js'
test: /\.js[x]?$/,
exclude: /node_modules/,
loader: 'babel-loader?presets[]=es2015&presets[]=react'
In webpack.config.js, module.loaders field is used to assign loaders. The above snippet uses babel-loader which also needs plugins
to transpile ES6 and React. You can also take another way to set the babel query option.
loaders: [
test: /\.jsx?$/,
exclude: /node_modules/,
loader: 'babel',
presets: ['es;, 'react']
Demo04: CSS-loader ()
Webpack allows you to require CSS in JS file, then preprocessed CSS file with CSS-loader.
require('./app.css');
background-color:
index.html
&script type=&text/javascript& src=&bundle.js&&&/script&
&h1&Hello World&/h1&
webpack.config.js
module.exports = {
entry: './main.js',
filename: 'bundle.js'
{ test: /\.css$/, loader: 'style-loader!css-loader' },
Attention, you have to use two loaders to transform CSS file. First is
to read CSS file, and another is
to insert Style tag into HTML page. Different loaders are linked by exclamation mark(!).
After launching the server, index.html will have inline style.
&script type=&text/javascript& src=&bundle.js&&&/script&
&style type=&text/css&&
background-color:
Demo05: Image loader ()
Webpack could also require images in JS files.
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
&script type=&text/javascript& src=&bundle.js&&&/script&
webpack.config.js
module.exports = {
entry: './main.js',
filename: 'bundle.js'
{ test: /\.(png|jpg)$/, loader: 'url-loader?limit=; }
transforms image files. If the image size is smaller than 8192 bytes, it will be transformed into Data URL; otherwise, it will be transformed into normal URL. As you see, question mark(?) is be used to pass parameters into loaders.
After launching the server, small.png and big.png will have the following URLs.
&img src=&data:image/base64,iVBOR...uQmCC&&
&img src=&b8bac1b2578.png&&
Demo06: CSS Module ()
css-loader?modules (the query parameter modules) enables the
It means your module's CSS is local scoped CSS by default. You can switch it off with :global(...) for selectors and/or rules. ()
index.html
&h1 class=&h1&&Hello World&/h1&
&h2 class=&h2&&Hello Webpack&/h2&
&div id=&example&&&/div&
&script src=&./bundle.js&&&/script&
:global(.h2) {
var React = require('react');
var ReactDOM = require('react-dom');
var style = require('./app.css');
ReactDOM.render(
&h1 className={style.h1}&Hello World&/h1&
&h2 className=&h2&&Hello Webpack&/h2&
document.getElementById('example')
webpack.config.js
module.exports = {
entry: './main.jsx',
filename: 'bundle.js'
test: /\.js[x]?$/,
exclude: /node_modules/,
loader: 'babel-loader',
presets: ['es;, 'react']
test: /\.css$/,
loader: 'style-loader!css-loader?modules'
Launch the server.
$ webpack-dev-server
Visit 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 ()
Webpack has a plugin system to expand its functions. For example,
will minify output(bundle.js) JS codes.
var longVariableName = 'Hello';
longVariableName += ' World';
document.write('&h1&' + longVariableName + '&/h1&');
index.html
&script src=&bundle.js&&&/script&
webpack.config.js
var webpack = require('webpack');
var uglifyJsPlugin = webpack.optimize.UglifyJsP
module.exports = {
entry: './main.js',
filename: 'bundle.js'
plugins: [
new uglifyJsPlugin({
compress: {
warnings: false
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 ()
This demo shows you how to load 3rd-party plugins.
could create index.html for you, and
could open a new browser tab when Webpack loads.
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',
filename: 'bundle.js'
plugins: [
new HtmlwebpackPlugin({
title: 'Webpack-demos'
new OpenBrowserPlugin({
url: 'http://localhost:;
Run webpack-dev-server.
$ webpack-dev-server
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 ()
You can enable some codes only in development environment with environment flags.
document.write('&h1&Hello World&/h1&');
if (__DEV__) {
document.write(new Date());
index.html
&script src=&bundle.js&&&/script&
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',
filename: 'bundle.js'
plugins: [devFlagPlugin]
Now pass environment variable into webpack.
# Linux & Mac
$ env DEBUG=true webpack-dev-server
$ DEBUG=true webpack-dev-server
Demo10: Code splitting ()
For big web apps it’s not efficient to put all code into a single file, Webpack allows you to split them into several chunks. Especially if some blocks of code are only required under some circumstances, these chunks could be loaded on demand.
At first, you use require.ensure to define a split point. ()
// 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.
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.
&script src=&bundle.js&&&/script&
webpack.config.js
module.exports = {
entry: './main.js',
filename: 'bundle.js'
Launch the server.
$ webpack-dev-server
On the surface, you won't feel any differences. However, Webpack actually builds main.js and a.js into different chunks(bundle.js and 1.bundle.js), and loads 1.bundle.js from bundle.js when on demand.
Demo11: Code splitting with bundle-loader ()
Another way of code splitting is using .
// 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 1.bundle.js.
Demo12: Common chunk ()
When multi scripts have common chunks, you can extract the common part into a separate file with CommonsChunkPlugin.
// 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
&div id=&a&&&/div&
&div id=&b&&&/div&
&script src=&init.js&&&/script&
&script src=&bundle1.js&&&/script&
&script src=&bundle2.js&&&/script&
webpack.config.js
var CommonsChunkPlugin = require(&webpack/lib/optimize/CommonsChunkPlugin&);
module.exports = {
bundle1: './main1.jsx',
bundle2: './main2.jsx'
filename: '[name].js'
test: /\.js[x]?$/,
exclude: /node_modules/,
loader: 'babel-loader',
presets: ['es;, 'react']
plugins: [
new CommonsChunkPlugin('init.js')
Demo13: Vendor chunk ()
You can also extract the vendor libraries from a script into a separate file with CommonsChunkPlugin.
var $ = require('jquery');
$('h1').text('Hello World');
index.html
&script src=&vendor.js&&&/script&
&script src=&bundle.js&&&/script&
webpack.config.js
var webpack = require('webpack');
module.exports = {
app: './main.js',
vendor: ['jquery'],
filename: 'bundle.js'
plugins: [
new monsChunkPlugin(/* chunkName= */'vendor', /* filename= */'vendor.js')
If you want a module available as variable in every module, such as making $ and jQuery available in every module without writing require(&jquery&). You should use ProvidePlugin ().
// main.js
$('h1').text('Hello World');
// webpack.config.js
var webpack = require('webpack');
module.exports = {
app: './main.js'
filename: 'bundle.js'
plugins: [
new webpack.ProvidePlugin({
$: &jquery&,
jQuery: &jquery&,
&window.jQuery&: &jquery&
Demo14: Exposing global variables ()
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 ().
For example, we have a data.js.
var data = 'Hello World';
We can expose data as a global variable.
// webpack.config.js
module.exports = {
entry: './main.jsx',
filename: 'bundle.js'
test: /\.js[x]?$/,
exclude: /node_modules/,
loader: 'babel-loader',
presets: ['es;, '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
Demo15: Hot Module Replacement ()
(HMR) exchanges, adds, or removes modules while an application is running without a page reload.
to enable Hot Module Replacement with the webpack-dev-server.
(1) Specify --hot and --inline on the command line
$ webpack-dev-server --hot --inline
Meaning of the options:
--hot: adds the HotModuleReplacementPlugin and switch the server to hot mode.
--inline: embed the webpack-dev-server runtime into the bundle.
--hot --inline: also adds the webpack/hot/dev-server entry.
(2) Modify webpack.config.js.
add new webpack.HotModuleReplacementPlugin() to the plugins field
add webpack/hot/dev-server and webpack-dev-server/client?http://localhost:8080 to the entry field
webpack.config.js looks like the following.
var webpack = require('webpack');
var path = require('path');
module.exports = {
'webpack/hot/dev-server',
'webpack-dev-server/client?http://localhost:;,
'./index.js'
filename: 'bundle.js',
publicPath: '/static/'
plugins: [
new webpack.HotModuleReplacementPlugin()
loaders: [{
test: /\.jsx?$/,
exclude: /node_modules/,
loaders: ['babel-loader'],
presets: ['es;, 'react']
include: path.join(__dirname, '.')
Now launch the dev server.
$ webpack-dev-server
Visiting http://localhost:8080, you should see 'Hello World' in your browser.
Don't close the server. Open a new terminal to edit App.js, and modify 'Hello World' into 'Hello Webpack'. Save it, and see what happened in the browser.
import React, { Component } from 'react';
export default class App extends Component {
render() {
&h1&Hello World&/h1&
import React from 'react';
import ReactDOM = require('react-dom');
import App from './App';
ReactDOM.render(&App /&, document.getElementById('root'));
index.html
&div id='root'&&/div&
&script src=&/static/bundle.js&&&/script&
Demo16: React router ()
This demo uses webpack to build 's official example.
Let's imagine a little app with a dashboard, inbox, and calendar.
+---------------------------------------------------------+
| +---------+ +-------+ +--------+
| |Dashboard| | Inbox | |Calendar|
Logged in as Jane |
| +---------+ +-------+ +--------+
+---------------------------------------------------------+
+---------------------+
+----------------------+
+---------&
+-------------&
+-+---+----+-----+----+
+----------------------+
+---------------------------------------------------------+
$ webpack-dev-server --history-api-fallback
Useful links
, by Pete Hunt
, by Web Design Weekly
, by Christian Alfoni
, by Cory House
, by Christian Alfoni
MIT相关热门文章

我要回帖

更多关于 amp lt 的文章

 

随机推荐