我爱编程程序员让前端飞

webpack实战3之异步加载js

2017-06-22  本文已影响0人  打铁大师

注意:

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

本文的目的是异步加载js

项目结构如下所示:

81498120603_.pic.jpg

开始实战

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

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

安装<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>Document</title>
</head>
<body>
    <div id="root"></div>
</body>
</html>

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

module.exports=function dom(elem){
   return document.querySelector(elem)
}

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

module.exports=function say(elem){
   console.log('今天天气真好');
}

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

require('./b')();
require.ensure([], function (require) {
    const dom = require('./a.js');
    dom('#root').innerHTML = 'hello world';
});

webpack 在构建时,会静态解析(statically parse)代码中的 require.ensure()。在其中任何被引用的依赖模块,或在回调函数中被 require() 的模块,都将被分离到一个新的 chunk 中。这个新的 chunk 会被生成为异步的 bundle,由 webpack 通过 jsonp 来按需加载。

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

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
    entry:'./index.js',
    output:{
        filename:'bundle.js',
        path:path.resolve(__dirname,'dist')
    },
    plugins:[
        new HtmlWebpackPlugin({
            template:'index.html',
            filename:'index.html',
            inject:'body'
        })
    ]
}

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

打包代码:‘

webpack --config webpack.config.js 

你会发现在dist文件夹中,生成了0.bundle.js,bundle.js,index.html

查看每个文件,你会发现,b.js和index.j的代码被打包到了bundle.js中。而a.js中的代码被打包到了0.bundle.js。
index.html中只包含了一个script标签( <script type="text/javascript" src="bundle.js"></script>),因为0.bundle.js将通过bundle.js异步加载。

上一篇下一篇

猜你喜欢

热点阅读