webpack实战2之js分离

注意:

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

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

项目结构如下所示:

webpack实战2之js分离_第1张图片
61498117491_.pic.jpg

开始实战

创建一个目录webpack-demo2,并安装wbepack

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

安装jquery

  npm install jquery --save

安装html-webpack-plugin

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

新建index.html文件




    
    
    
    webpack




新建index.js文件

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

新建webpack.config.js文件

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

webpack实战2之js分离_第2张图片
71498118152_.pic_hd.jpg

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

你可能感兴趣的:(webpack实战2之js分离)