webpack使用初体验(爽)

来源:互联网 发布:音轨合成软件下载 编辑:程序博客网 时间:2024/05/22 12:06

// 鉴于看的英文文档,本篇将包含大量英文引用 ✍️

Getting Started

webpack is used to compile JavaScript modules.Once intstalled,we can interface with webpack either from its CLI or API.

Basic Setup

First Let’s creat a directory, initialize npm and install webpack locally:

mkdir webpack-demo && cd webpack-demonpm init -ynpm install --save-dev webpack

ps:由于对npm不熟悉(很快会的),所以看了下 npm init主要是生成package.json文件让我们去配置。而npm install –save-dev webpack意思是我们安装了这个包并且把它的基本信息写入目录的package.json文件。

Now we’ll create the following directory structure and contents:

project

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

src/index.js

function component() {    var element= document.createElement('div')    // Lodash, currently included via a scripts required for this line to work    element.innerHTML = _.join(['Hello', 'webpack'], ' ');    return element;}document.body.appendChild(component());

ps:记得以前就看过的一些dom操作,简单说就是建了一个< div >标签,然后往里面插了一行” Hello webpack”的文本。

这里用到的Lodash是一个具有一致接口,模块化,高性能等特性的Javascript工具库。http://lodashjs.com/docs/(像之前国庆手码过的underscore就是被它埋没了下去)

index.html

<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>

In this example, there are implicit dependencies between the < script > tags. Our index.js file depends on lodash being included in the page before it runs. This is because index.js never declared a need for lodash; it just assumes that the global variable _ exists.

There are problems with managing JavaScript projects this way:

  1. It is not immediately apparent that the script depends on an external library.
  2. If a dependency is missing, or included in the wrong order, the application will not function properly.
  3. If a dependency is included but not used, the browser will be forced to download unnecessary code.

简而言之:上面的< script > 标签中有隐式依赖。在运行index.js之前我们就用了loadsh库,index.js没有声明要用loadsh,仅仅是假设了变量_存在。如果我们真的以这种方式来管理JavaScript项目,会带来以下问题:
1. 并没有即时体现出脚本用了外部依赖。
2. 如果依赖缺失或者顺序错了那么应用就不能正常跑
3. 如果包含了这个依赖但是却没用,浏览器会被强制下载多余代码。


好啦。废话这么多,现在是时候让我们的webpack出手解救你们愚蠢的人类了!


Creating a Bundle

tweak our directory structure slightly, separating the “source” code (/src) from our “distribution” code (/dist).

The “source” code is the code that we’ll write and edit.
The “distribution” code is the minimized and optimized output of our build process that will eventually be loaded in the browser:

就是说/src是我们写代码的文件。/dist是我们最小和优化之后最终输出在浏览器上的文件。

project

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

给index.js绑定lodash依赖,在本地安装库

npm install --save lodash

然后引入到我们的脚本中:

src/index.js

+ import _ from 'lodash';+  function component() {    var element = document.createElement('div');-   // Lodash, currently included via a script, is required for this line to work+   // Lodash, now imported by this script    element.innerHTML = _.join(['Hello', 'webpack'], ' ');    return element;  }  document.body.appendChild(component());

ps:import _ from ‘lodash’报错说js版本不支持,打开ide发现js的版本是ECMAScript5.1,改为ECMAScript6就好了。真的好有趣啊hhhhhh,看来我们还是要紧随潮流哇 = 3=

现在,既然我们解决了index.js中的隐式依赖问题,我们就可以修改index.html了。移除lodash的< script > 标签,导入将index.js打包好的bundle.js文件。

dist/index.html

<html>    <head>     <title>Getting Started</title>    </head>    <body>        <script src="bundle.js"></script>    </body></html>

在这个设置中,index.js明确要求lodash存在,并将其绑定为_(没有全局范围污染)。通过指出模块需要什么依赖关系,webpack可以使用这些信息来构建依赖关系图。然后使用该图生成一个优化的包,其中脚本将以正确的顺序执行。

let’s run webpack with our script as the entry point and bundle.js as the output:

//命令行./node_modules/.bin/webpack src/index.js dist/bundle.js

运行成功啦 ~!!激动,人生第一个自己用webpack打包运行的项目。
此处推荐阅读: http://www.jianshu.com/p/42e11515c10f


Using a Configuration

PS:棒耶✌️ webpack configuration终于到啦,现在我们可以不用cli而通过创建一个webpack.config,js来配置。这将会提供更复杂和更有效的配置

project

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

webpack.config.js

const path = require('path');module.exports = {    entry: './src/index.js',    output: {        filename: "bundle.js",        path: path.resolve(__dirname, 'dist')    }};

run the build again but instead using our new configuration:

./node_modules/.bin/webpack --config webpack.config.js

A configuration file allows far more flexibility than simple CLI usage. We can specify loader rules, plugins, resolve options and many other enhancements this way.


NPM Scripts

鉴于从CLI运行webpack的本地副本并不是特别有趣,我们可以设置一个小捷径。让我们通过添加一个npm脚本来调整我们的package.json:(听起来好有趣是不是?)

package.json

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

Now the npm run build command can be used in place of the longer commands we used earlier. Note that within 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 call webpack, instead of ./node_modules/.bin/webpack (我还试了把build改为caojiali,是有多无聊嘻嘻)


总结: 啦啦啦 ~ webpack基础内容也就到这儿啦。其实很简单的东西但是全身心投入进去也能获得极大的满足感。开心 ~

原创粉丝点击