webpack进阶

10次阅读

共计 2318 个字符,预计需要花费 6 分钟才能阅读完成。

基于 webpack 提供的接口,社区可以贡献各种 loader 和 plugin,组合使用可以使得 webpack 的功能很丰富强大。

常用 loader

  • sass-loader,css-loader,style-loader => 加载样式
  • url-loader => 加载文件,如字体文件和图片文件
  • html-loader => 加载模板文件
  • babel-loader => 加载 js 和 jsx 文件
  • awesome-typescript-loader => 加载 ts 文件

常用 Plugin

html-webpack-plugin

  1. 安装依赖
npm install html-webpack-plugin --save-dev
  1. 配置 modules
// webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin')

module.exports = {
  // ...
  modules:[
    new HtmlWebpackPlugin({
      template:'./index.html', // 引用的模板
      filename:'index.html', // 打包后的命名
      inject:true, // 是否自动引入打包的 js 文件
    })
  ]
}
  1. 引用中的模板(index.html)可以使用一些变量及简单的分支
// index.html
<% if(process.env.NODE_ENV==='development'){ %>
    1313
<% } %>
<script>
   console.log(<%= JSON.stringify(process) %>);
   console.log(<%= JSON.stringify(process.env) %>);
</script>

其中 JSON.stringify(process),解析为一个 对象 ,JSON.stringify(process.env) 为 空对象

<script>
      console.log({"title":"browser","browser":true,"env":{},"argv":[],"version":"","versions":{}});
      console.log({});
</script>

这时候的 process.env.NODE_ENV 是为 undefined,需要手动设置其值,看 webpack.DefinePlugin ⤵️。

  1. 与 html-loader 冲突的问题,如果使用了 html-loader 加载 .html 后缀文件,将不会处理 <% %> 规则。HtmlWebpackPlugin 的 template 使用别的后缀,将原模板的后缀相应更改即可。
// webpack.config.js
const HtmlWebpackPlugin = require('html-webpack-plugin')
module.exports = {
  module:{
    rules:[
      {
        test:/\.html$/,
        loader:'html-loader'
      }
    ]
  },
  plugins:[
    new HtmlWebpackPlugin({
      template:'index.htm', // 这里后缀改成和 .html 不一样的
      filename:'index.html',
      inject:true,
    })
  ]
}

webpack.DefinePlugin

配置一些全局变量,开发和打包过程中,直接将代码中相应的变量变成配置的值。值需要进行 JSON.stringify 处理。

// webpack.config.js
const wepback = require('webpack')

module.exports = {
  plugins:[
    new webpack.DefinePlugin({
      'process.env':{'NODE_ENV':JSON.stringify('development')
            },
      'BASE_URL':JSON.stringify('https://haokur.com')
    })
  ]
}
// index.htm
<%if(process.env.NODE_ENV==='development'){%>
      123
<%}%>
<script>
      console.log(<%= process %>);
      console.log(<%= JSON.stringify(process) %>);
      console.log(<%= JSON.stringify(process.env) %>);
      console.log(<%= BASE_URL %>);
</script>
// main.js
console.log(BASE_URL);

打包后:

<!-- 打包后的代码,dist/index.html --> 
123
<script>
    console.log([object Object]);
    console.log({"title":"browser","browser":true,"env":{},"argv":[],"version":"","versions":{}});
    console.log({"NODE_ENV":"development"});
    console.log(https://haokur.com);
</script>
// 打包后的 main.js
console.log('https://haokur.com')
  • <%if %> 判断,判断为真,则显示里面内容,否则忽略;
  • <%= process %> 直接解析出来,为 [object Object]
  • BASE_URL 解析出来的没有加上两边的引号,但在 js 中解析成字符串会加上两边的冒号
  • 非 HtmlWebpackPlugin.template 定义的模板页的除 js 之外的其他文件,不支持此解析功能

待续

正文完
 0