webpack实战2之js分离

注意:

本文假设你有webpack2 的基础认识。

本文的目的是分离第三方代码和自身代码

项目结构如下所示:

61498117491_.pic.jpg

开始实战

创建一个目录<code>webpack-demo2</code>,并安装<code>wbepack</code>。

  mkdir webpack-demo2 && cd webpack-demo2
  npm init -y
  npm install --save-dev webpack

安装<code>jquery</code>

  npm install jquery --save

安装<code>html-webpack-plugin</code>

npm install html-webpack-plugin --save-dev

新建<code>index.html</code>文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=<device-width>, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>webpack</title>
</head>
<body>
</body>
</html>

新建<code>index.js</code>文件

const $ = require('jquery');
$('body').html('hello world').css('color','red');

新建<code>webpack.config.js</code>文件

const path = require('path');
const webpack = require('webpack');
const HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
entry: {
    main: './index.js',
    vendor: 'jquery'
},
output: {
    filename: '[name].js',
    path: path.resolve(__dirname, 'dist')
},
plugins: [
    new webpack
        .optimize
        .CommonsChunkPlugin({
            name: ['vendor']
        }),
        new HtmlWebpackPlugin({
            filename:'index.html',
            template:'index.html',
            inject:'body'
        })
    ]
}

说明
上述代码使用了多个入口。

webpack.optimize.CommonsChunkPlugin 插件,是一个可选的用于建立一个独立文件(又称作 chunk)的功能,这个文件包括多个入口 chunk 的公共模块。通过将公共模块拆出来,最终合成的文件能够在最开始的时候加载一次,便存起来到缓存中供后续使用。

HtmlWebpackPlugin该插件将所有生成的js文件自动引入index.html中。当文件名带有hash值时,这个插件尤其有用。
HtmlWebpackPlugin会根据模版生成一个新的html文件。

最后打包代码:

webpack --config webpack.config.js

71498118152_.pic_hd.jpg

在浏览器中打开dist文件夹下的index.html就能看到效果了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 最近在学习 Webpack,网上大多数入门教程都是基于 Webpack 1.x 版本的,我学习 Webpack 的...
    My_Oh_My阅读 8,219评论 40 247
  • GitChat技术杂谈 前言 本文较长,为了节省你的阅读时间,在文前列写作思路如下: 什么是 webpack,它要...
    萧玄辞阅读 12,726评论 7 110
  • 无意中看到zhangwnag大佬分享的webpack教程感觉受益匪浅,特此分享以备自己日后查看,也希望更多的人看到...
    小小字符阅读 8,253评论 7 35
  • 写在开头 先说说为什么要写这篇文章, 最初的原因是组里的小朋友们看了webpack文档后, 表情都是这样的: (摘...
    Lefter阅读 5,340评论 4 31
  • 西子是常年在外奔波的设计师,住酒店的时间可能比在家里的时间还长。上海、北京、广州这些大都市的酒店全都被他睡了个遍,...
    033e741a6890阅读 735评论 0 1