webpack入门(3)

自动化生成项目中html页面

这里我们可以用到一个插件,叫做html-plugin

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

我们继续在webpack.config.js中配置,在配置中使用的key是plugins,需要通过数组进行初始化

   var htmlWebpackPlugin = require('html-webpack-plugin');
   module.exports = {
      //...省略output等
      plugins: [
         new htmlWebpackPlugin()
      ]
   }

我们重新运行脚本npm run webpack(假设在npm的scripts配置中加入了脚本配置),会看到信息中显示

    html-webpack-plugin for "index.html"

这时output中的内容已经被包含在了index.html中。我们还可以对它进行配置模板

   module.exports = {
      //...省略output等
      //这里上下文为根目录
      plugins: [
         new htmlWebpackPlugin({
            filename: 'index-[hash].html',
            template: template.html,
            //把output文件注入到head标签中
            inject: 'head'
         })
      ]
   }

这里配置的上下文为根目录,所以我们这里的模板template.html就是放在根目录下,重新run之后,新生成的文件会套用template.html的模板

使用loaders

比如我们在app.js中引入一个我们自定义的hello组件

   import hello from './components/hello'
   const App = function(){
      console.log(hello)
   }
   new App();

我们在hello中分别定义hello.js,hello.less,hello.html定义相应的内容。

   //hello.html
   <div class="hello">
       <div>This is a hello component</div>
   </div>
   //hello.js
   import tpl from './hello.html'
   function hello(){
      return {
         name: 'hello',
         tpl: tpl
      }
   } 
   export default hello;

那么在我们的config中

   module.export = {
       entry: './src/app.js',
       output: {
          path: './dist',
          filename: 'js/[name].bundle.js'
       },
       plugins: [
         new htmlWebpackPlugin({
             filename: 'index.html',
             template: 'template.html',
             inject: body
     })
      ]
   }

那么回到我们正题loader ,loader是什么,比如你有一些非正常js的文件,如ES6的文件,JSX等,你可以告诉webpack怎么去加载它。loader可以被串联,比如我们之前串联css-loader和style-loader。loader可以是异步的。
我们直接可以在配置文件中加上module来配置loaders属性

   module: {
      loaders: [
         //test是正则匹配,以js结尾的等
         { 
            test: /\.js$/, 
            loader: 'babel-loader',
            presets: ['es2015']
         }
         { test: /\.jade$/, loader: "jade" },
         { test: /\.css$/, loader: 'style!css'}
      ]
   }

babel转义的时候,我们可以使用presets对ES6支持语法的范围进行设定,在npm中需要对presets所指定的范围进行安装。这时候使用run,我们就会发现babel通过loaders进行了转化。

使用exclude

虽然我们成功使用了babel,但是会发现现在打包操作非常慢,这时候我们就会使用module的其他参数比如exclude

   module: {
      loaders: [
         //test是正则匹配,以js结尾的等
         { 
            test: /\.js$/, 
            loader: 'babel-loader'//不转义node_modules下的依赖
            exclude: './node_modules/',
            presets: ['es2015']
         }
      ]
   }

这样速度就明显得到了提升

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值