webpack 入门例子

来源:互联网 发布:c语言 纸牌 编辑:程序博客网 时间:2024/06/11 00:24

https://webpack.js.org/guides/getting-started/

     webpack作为打包工具,支持commonJS、AMD、ES6模块规范,我们可以使用它将多个HTML、CSS、js打包等单个或者多个文件,以减少http请求。不仅如此,webpack还可以将代码分割,按需加载文件。、

一、 开始

   你也许已经知道,webpack 通常用来编译JavaScript modules。一旦安装,你能和webpack 交互,或者来自 CLI or API. If you're still new to webpack, please read through the core concepts and this comparison to learn why you might use it over the other tools that are out in the community.

二、Basic Setup创建项目目录、初始化npm、安装webpack  

 1>mkdir webpack-demo && cd webpack-demo//建立一个目录
2>npm init -y  //初始化
3>

npm install --save-dev webpack  //本地安装webpack发现出错,在windows下先安装
npm install -g jshint:主要保存在user Appdata下面有一些数据
再安装
npm install --save-dev webpack  //本地安装webpack发现出错,在windows下先安装
:在这里安装时,会读取user Appdata里面的数据
不知道什么原因?

三、建立一个简单工程,目录如下

webpack-demo  |- package.json+ |- index.html+ |- /src+   |- index.js

lodash@4.16.6
1、建立src/index.js  
function component() {  var element = document.createElement('div');  // Lodash, currently included via a script, is required for this line to work  element.innerHTML = _.join(['Hello', 'webpack'], ' ');  return element;}document.body.appendChild(component());
2、建立index.html,并引进index.js
<html>  <head>    <title>Getting Started</title>    <script src="https://unpkg.com/lodash@4.16.6"></script>  </head>  <body>    <script src="./src/index.js"></script>  </body></html>
在index.html 例子中,两个 <script> 标签存在着依赖。index.js文件依赖 lodash,这是因为index.js从来没有表示需要lodash的;lodash认为是全局变量。

这种方式管理js有几个问题:

  • 脚本依赖外部库,并不明显。
  • 如果一个依赖丢失了,或顺序错了,哪么一个应用将出现问题。
  • 如果包含一个依赖,没有使用,浏览器将强迫下载一个不必要的代码,即冗余也浪费时间。

四、 webpack 建立工程,管理这些js,上面工程稍加修改

  Creating a Bundle

     首先,我们将稍微来调整我们的目录结构,加一个发布目录/dist,建立一个index.html放在下面,即把原代码和发布代码分开,源码是我们写和编辑的代码,发布代码是最终浏览器加载的最小及最优化代码

  1、  project

webpack-demo  |- package.json+ |- /dist+   |- index.html- |- index.html  |- /src    |- index.js
 绑定 index.js 依赖 lodash.js ,我们需要安装lodash,

  2、D:\setupsoft\nodejs\webpack-demo>npm install --save lodash

   然后修改 src/index.js,加下面一句 里面,而以前是直接放在script里,这样从字数上来简单多了,而且像java一样

这一句和node.js的require()应该一样?全是一个js文件需要其它js文件,导入进来。

 import _ from 'lodash';
现在,因为我们已经绑定了我们的脚本,我们必须修改我们的index.html 文件. 删除lodash <script>, 因为我们现在导入了这个脚本, 3、import it,修改另一个 <script>标签去装载绑定, 代替 raw /src 文件:

<html>
   <head>
     <title>Getting Started</title>
   </head>
   <body>
   <script src="bundle.js"></script>
   </body>
  </html>
在这种安装中, index.js 确定需要 lodash 出现, 并且用 _ 绑定它 (no global scope pollution).通过说明一个模块需要什么依赖, webpack 能使用这个信息去绑定一个依赖图, 然后使用图形去产生一个优化绑定,哪里脚本将按正确的顺序执行。

也就是说,让我们运行webpack,用我们 script 作为输入, bundle.js所为输出。

4、D:\setupsoft\nodejs\webpack-demo\node_modules\.bin>webpack ../../src/index.js ../../dist/bundle.js,

在dist发布目录建立一个bundle.js包

Hash: 5091f71fee92b3f8f6e9
Version: webpack 3.4.1
Time: 452ms
    Asset    Size  Chunks                    Chunk Names
bundle.js  544 kB       0  [emitted]  [big]  main
   [0] D:/setupsoft/nodejs/webpack-demo/src/index.js 296 bytes {0} [built]
   [1] ../lodash/lodash.js 540 kB {0} [built]
   [2] ../webpack/buildin/global.js 509 bytes {0} [built]
   [3] ../webpack/buildin/module.js 517 bytes {0} [built]

5、Your output may vary a bit, but if the build is successful then you are good to go.

在你的浏览器打开 index.html  if everything went right, you should see the following text: 'Hello webpack'.



总结:上面就是把一个网页有依赖关系的的几个js,经过打包,然后生成一个bundle.js,引入到html中

          优点:1》可以加快浏览器取到一个文件速度,用户的响应时间缩短

                     2》减少页面的代码量。

                     3>而且字节数变少了。

Modules:

   The import and export 语句在ES2015在被标准化。然而在大多数浏览器尽管并不被支持 , webpack 并不支持他们 out of the box.

在这种情况下, webpack 实际上 "transpiles" 转换代码,以便于老的浏览器也能运行它。如果你查看dist/bundle.js, 你也许能看见webpack如何做这件事, it's quite ingenious!

除了import and export, webpack 支持各种其它的模板语法, seeModule API for more information.

注:除了import and export 语句,webpack 并不改变任何代码,如果你正在使用其它的ES2015 features, 确定使用use a transpiler such asBabel orBublé via webpack'sloader system.


五、使用配置文件建立工程,

  大多数工程将需要一个更复杂的安装,这就webpack支持一个配置文件的原因。这个比控制台打许多命令更有效,
因此让我建立一个替代上面使用得CLI选项。

  1、project

  加一个 webpack.config.js

webpack-demo  |- package.json+ |- webpack.config.js  |- /dist    |- index.html  |- /src    |- index.js
webpack.config.js  
const path = require('path');//导入path下的所有文件,是importmodule.exports = {  entry: __dirname+'/src/index.js',    output: {    filename: 'bundle.js',//出    path: path.resolve(__dirname, 'dist')//全局变量,取得dist文件夹目录  }};
现在,让我们再一次使用我们新的配置文件建立bundle.js:

./node_modules/.bin/webpack --config webpack.config.jsHash: ff6c1d39b26f89b3b7bbVersion: webpack 2.2.0Time: 390ms    Asset    Size  Chunks                    Chunk Namesbundle.js  544 kB       0  [emitted]  [big]  main   [0] ./~/lodash/lodash.js 540 kB {0} [built]   [1] (webpack)/buildin/global.js 509 bytes {0} [built]   [2] (webpack)/buildin/module.js 517 bytes {0} [built]   [3] ./src/index.js 278 bytes {0} [built]

如果一个webpack.config.js 存在, the webpack 命令 默认的选择它. 这里我们使用--config选项,仅仅去显示

你能用一些name进行配置. 这个迟早用得上,为更复杂的配置,这个配置需要拆分成多个文件。

 一个配置文件允许更灵活比简单的CLI使用。我们能够指定装载规则,插件,

resolve options and many other enhancements this way. See theconfiguration documentation to learn more.

NPM Scripts

 我们让上面命令更短:npm run buildh,是不是短很多,配置如下。

我们可以通过npm script:修改package.json

package.json  

{  ...  "scripts": {    "build": "webpack"  },  ...}

现在 npm运行build 命令。 Note 在scripts里 we can reference locally installed npm packages by name instead of writing out the entire path. 、

This convention is the standard in most npm-based projects and allows us to directly callwebpack, instead of./node_modules/.bin/webpack

Now run the following command and see if your script alias works:

npm run buildhHash: ff6c1d39b26f89b3b7bbVersion: webpack 2.2.0Time: 390ms    Asset    Size  Chunks                    Chunk Namesbundle.js  544 kB       0  [emitted]  [big]  main   [0] ./~/lodash/lodash.js 540 kB {0} [built]   [1] (webpack)/buildin/global.js 509 bytes {0} [built]   [2] (webpack)/buildin/module.js 517 bytes {0} [built]   [3] ./src/index.js 278 bytes {0} [built]
Custom parameters can be passed to webpack by adding two dashes between the npm run build command and your parameters, e.g. npm run build -- --colors.

Conclusion

Now that you have a basic build together you should move on to the next guide Asset Management to learn how to manage assets like images and fonts with webpack. At this point, your project should look like this:

project

webpack-demo|- package.json|- webpack.config.js|- /dist  |- bundle.js  |- index.html|- /src  |- index.js|- /node_modules
If you're using npm 5, you'll probably also see a package-lock.json file in your directory.

If you want to learn more about webpack's design, you can check out the basic concepts and configuration pages. Furthermore, the API section digs into the various interfaces webpack offers.





 
原创粉丝点击