Webpack1 入门+实战

  1. 首先在桌面新建一个 webpacktest 文件夹
  2. 打开命令行工具,进入 webpacktest 文件夹中
cd Desktop
cd webpacktest
  1. 安装 webpack
//先在全局安装
cnpm install webpack -g
//再在项目中安装
cnpm install webpack --save-dev
  1. 在项目中新建一个 webpack.config.js 文件
    编辑 webpack.config.js 文件
var webpack = require('webpack');
console.log(webpack);//测试 webpack 是否安装成功
  1. 在命令行中运行,查看输出是否成功
    node webpack.config.js

输出如下图所示的一个对象 即表示成功了


image.png
  1. 接下来就是引入比较核心的东西
var webpack = require('webpack');
//最核心的模块,所有的东西都要在这里面进行
module.exports = {

}
  1. 接下来就要建网站了,一般是通过这样的形式:在项目中新建 src 和 build 文件夹
    文件是在 src 文件夹中编辑然后 build 到 build 文件夹中 上线上的是 build 文件夹
    文件结构如下

src -> stylesheets -> index.css
src -> scripts -> app.js
src -> scripts -> index.js
src -> index.html
build -> stylesheets
build -> scripts

  1. 开始编辑文件
    index.js
var s = function(data) {
    //console.warn 向web 控制台输出一条警告信息
    console.warn(data);
}
//切记这里要按照模块的规范一样将要导出的东西导出,这里我们将函数 s 导出去了
module.exports.fn = s;

app.js

var index = require('./index.js');
index.fn('init index');

index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>第一个webpacktest</title>
</head>
<body>
    Hello Webpack
</body>
</html>

index.css

body{
    background: black;
    color: green;
}

webpack.config.js

var webpack = require('webpack');
// console.log(webpack);//测试 webpack 是否安装成功   

//最核心的模块,所有的东西都要在这里面进行
module.exports = {
    //配置入口资源
    //它的值可以是对象也可以是单一的一个
    entry:__dirname + 'src/scripts/app.js',
    //配置编译后的资源
    //将编译后的资源放到哪去
    output:{
        path:__dirname + 'build/scripts',
        //hash 表示的是:平常的 index.js 编译后就变成了 index.assxx.js
        filename:'[name]-[hash].js'
    }
}
  1. 在命令行中 webpacktest 目录下运行程序
webpack

显示如下图所示代表执行成功了

image.png
  1. 到项目中的 build -> scripts 文件夹中查看会发现多了一个编译后的 .js 文件
/******/ (function(modules) { // webpackBootstrap
/******/    // The module cache
/******/    var installedModules = {};
/******/
/******/    // The require function
/******/    function __webpack_require__(moduleId) {
/******/
/******/        // Check if module is in cache
/******/        if(installedModules[moduleId]) {
/******/            return installedModules[moduleId].exports;
/******/        }
/******/        // Create a new module (and put it into the cache)
/******/        var module = installedModules[moduleId] = {
/******/            i: moduleId,
/******/            l: false,
/******/            exports: {}
/******/        };
/******/
/******/        // Execute the module function
/******/        modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
/******/
/******/        // Flag the module as loaded
/******/        module.l = true;
/******/
/******/        // Return the exports of the module
/******/        return module.exports;
/******/    }
/******/
/******/
/******/    // expose the modules object (__webpack_modules__)
/******/    __webpack_require__.m = modules;
/******/
/******/    // expose the module cache
/******/    __webpack_require__.c = installedModules;
/******/
/******/    // define getter function for harmony exports
/******/    __webpack_require__.d = function(exports, name, getter) {
/******/        if(!__webpack_require__.o(exports, name)) {
/******/            Object.defineProperty(exports, name, {
/******/                configurable: false,
/******/                enumerable: true,
/******/                get: getter
/******/            });
/******/        }
/******/    };
/******/
/******/    // getDefaultExport function for compatibility with non-harmony modules
/******/    __webpack_require__.n = function(module) {
/******/        var getter = module && module.__esModule ?
/******/            function getDefault() { return module['default']; } :
/******/            function getModuleExports() { return module; };
/******/        __webpack_require__.d(getter, 'a', getter);
/******/        return getter;
/******/    };
/******/
/******/    // Object.prototype.hasOwnProperty.call
/******/    __webpack_require__.o = function(object, property) { return Object.prototype.hasOwnProperty.call(object, property); };
/******/
/******/    // __webpack_public_path__
/******/    __webpack_require__.p = "";
/******/
/******/    // Load entry module and return exports
/******/    return __webpack_require__(__webpack_require__.s = 0);
/******/ })
/************************************************************************/
/******/ ([
/* 0 */
/***/ (function(module, exports, __webpack_require__) {

var index = __webpack_require__(1);
index.fn('init index');

/***/ }),
/* 1 */
/***/ (function(module, exports) {

var s = function(data) {
    //console.warn 向web 控制台输出一条警告信息
    console.warn(data);
}
//切记这里要按照模块的规范一样将要导出的东西导出,这里我们将函数 s 导出去了
module.exports.fn = s;

/***/ })
/******/ ]);
  1. 这个时候需要在 html 中将这个编译过后的 .js 文件引过来,需要安装一个包 html-webpack-plugin

参考链接:https://www.npmjs.com/package/html-webpack-plugin

npm install html-webpack-plugin --save-dev
  1. 配置插件 plugins
    编辑 webpack.config.js 文件
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
// console.log(webpack);//测试 webpack 是否安装成功   

//最核心的模块,所有的东西都要在这里面进行
module.exports = {
    //配置入口资源
    //它的值可以是对象也可以是单一的一个
    entry: __dirname + '/src/scripts/app.js',
    //配置编译后的资源
    //将编译后的资源放到哪去
    output: {
        path: __dirname + '/build',
        //hash 表示的是:平常的 index.js 编译后就变成了 index.assxx.js
        filename: 'scripts/[name]-[hash].js'
    },
    plugins: [
        new HtmlWebpackPlugin({ // Also generate a test.html 
            filename: 'index.html',
            template: __dirname + '/src/index.html'
        })
    ]
}
  1. 命令行中执行
webpack

结果如下图所示,证明成功了


image.png
  1. 此时去查看 build 文件夹,会发现多了一个 index.html 文件
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>第一个webpacktest</title>
</head>
<body>
    Hello Webpack
<script type="text/javascript" src="scripts/main-dc8843a6a69bfa4cd69e.js"></script></body>
</html>

在浏览器中打开 index.html 页面 会如下图显示

image.png
  1. 配置别名 resolve
    编辑 webpack.config.js 文件
var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
// console.log(webpack);//测试 webpack 是否安装成功   

//最核心的模块,所有的东西都要在这里面进行
module.exports = {
    //配置入口资源
    //它的值可以是对象也可以是单一的一个
    entry: __dirname + '/src/scripts/app.js',
    //配置编译后的资源
    //将编译后的资源放到哪去
    output: {
        path: __dirname + '/build',
        //hash 表示的是:平常的 index.js 编译后就变成了 index.assxx.js
        filename: 'scripts/[name]-[hash].js'
    },
    plugins: [
        new HtmlWebpackPlugin({ // Also generate a test.html 
            filename: 'index.html',
            template: __dirname + '/src/index.html'
        })
    ],
    resolve:{
        extensions:['.js','.css']
    }
}

然后修改 app.js 文件第一行

var index = require('./index');

将 build ->scripts 中的两个编译后的 .js 文件删掉

再在命令行中执行程序

webpack

如下图所示即表示成功了

image.png
  1. 接下来开始引入 css 文件
    编辑 app.js 文件
var index = require('./index');
require('../stylesheets/index');
index.fn('init index');

此时运行程序

webpack

会报如下所示的错误

image.png

这个报错是因为对 css 文件编译失败了需要另一个 loader

  1. 资源处理 module 模块
    css 处理后实际上会被打包到 js 里

编辑 webpack.config.js 文件

var webpack = require('webpack');
var HtmlWebpackPlugin = require('html-webpack-plugin');
// console.log(webpack);//测试 webpack 是否安装成功   

//最核心的模块,所有的东西都要在这里面进行
module.exports = {
    //配置入口资源
    //它的值可以是对象也可以是单一的一个
    entry: __dirname + '/src/scripts/app.js',
    //配置编译后的资源
    //将编译后的资源放到哪去
    output: {
        path: __dirname + '/build',
        //hash 表示的是:平常的 index.js 编译后就变成了 index.assxx.js
        filename: 'scripts/[name]-[hash].js'
    },
    //配置插件
    plugins: [
        new HtmlWebpackPlugin({ // Also generate a test.html 
            filename: 'index.html',
            template: __dirname + '/src/index.html'
        })
    ],
    //资源处理
    module: {
        loaders: [{
            //后面是正则匹配所有已 css 结尾的文件
            test: /\.css$/,
            //这里要装两个 loader 两个loader 之间的 感叹号是联合起来
            loader: 'style-loader!css-loader'
        }]
    },
    //配置扩展名
    resolve: {
        extensions: ['.js', '.css']
    }
}

此时运行程序

webpack

会报出如下图所示的错误

image.png

这个错是因为我们并没有安装所使用的 loader

接下来进行安装两个 loader

cnpm install css-loader --save
cnpm install style-loader --save

装完之后在执行

webpack

如下图所示表示成功了

image.png

此时在浏览器中打开 build -> index.html 文件,css js 什么的就都有了

image.png
  1. 总结:
    loader 的用法
image.png
  1. 用 require 的方式


    image.png
  2. 在 webpack.config.js 文件中配置


    image.png
  3. 通过命令行的方式


    image.png

    常见的 loader


    image.png
  1. webpack 使用优化
image.png

image.png

image.png

image.png

image.png

image.png

image.png

webpack 主要的就是 webpack.config.js 中五个模块的配置。

参考链接:http://webpack.github.io/ webpack 官网

webpack 2


image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 218,386评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,142评论 3 394
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,704评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,702评论 1 294
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,716评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,573评论 1 305
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,314评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,230评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,680评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,873评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,991评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,706评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,329评论 3 330
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,910评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,038评论 1 270
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,158评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,941评论 2 355

推荐阅读更多精彩内容