在前面我们已经大概说过他们的作用了。
在这一节中,我们会对他的更多需求进行补充。

多个入口文件打包

假设现在,我们希望把之前的js文件反复打包多次,应该怎么处理。

  1. const path = require('path')
  2. const HtmlWebpackPlugin = require('html-webpack-plugin')
  3. const { CleanWebpackPlugin } = require("clean-webpack-plugin");
  4. module.exports = {
  5. mode: 'development',
  6. entry: {
  7. // entry对象中,创建两个入口文件
  8. main: './src/index.js',
  9. sub: './src/index.js'
  10. },
  11. module: {
  12. rules:[
  13. {
  14. test: /\.(jpg|png|gif)$/,
  15. use:{
  16. loader: 'url-loader',
  17. options: {
  18. name:'[name]_[hash].[ext]',
  19. outputPath: 'images/',
  20. limit: 2048 // 2kb
  21. }
  22. }
  23. },
  24. {
  25. test: /\.scss$/,
  26. use:[
  27. 'style-loader',
  28. {
  29. loader:'css-loader',
  30. options: {
  31. importLoaders: 2
  32. }
  33. },
  34. 'sass-loader',
  35. 'postcss-loader'
  36. ]
  37. }
  38. ]
  39. },
  40. plugins:[new HtmlWebpackPlugin({
  41. template: 'src/index.html'
  42. }), new CleanWebpackPlugin()],
  43. output: {
  44. // filename: 'bundle.js',
  45. filename: '[name].js',
  46. path: path.resolve(__dirname, 'dist')
  47. }
  48. }

打包成功
image.png
并且在我们的index.html中同时引入这两个文件,
因为我们使用了htmlWebpackPlugin,他发现了现在我们打包要输出两个文件,
这个时候他就会把这两个文件都放到index.html中
image.png

还有一种场景,例如我们很多时候希望把index.html文件打包给后端,作为后端的入口文件
但是js文件可能放到其他服务器。
那么index.html中的js文件引入肯定是需要加上绝对地址的。

  1. const path = require('path')
  2. const HtmlWebpackPlugin = require('html-webpack-plugin')
  3. const { CleanWebpackPlugin } = require("clean-webpack-plugin");
  4. module.exports = {
  5. mode: 'development',
  6. entry: {
  7. // entry对象中,创建两个入口文件
  8. main: './src/index.js',
  9. sub: './src/index.js'
  10. },
  11. module: {
  12. rules:[
  13. {
  14. test: /\.(jpg|png|gif)$/,
  15. use:{
  16. loader: 'url-loader',
  17. options: {
  18. name:'[name]_[hash].[ext]',
  19. outputPath: 'images/',
  20. limit: 2048 // 2kb
  21. }
  22. }
  23. },
  24. {
  25. test: /\.scss$/,
  26. use:[
  27. 'style-loader',
  28. {
  29. loader:'css-loader',
  30. options: {
  31. importLoaders: 2
  32. }
  33. },
  34. 'sass-loader',
  35. 'postcss-loader'
  36. ]
  37. }
  38. ]
  39. },
  40. plugins:[new HtmlWebpackPlugin({
  41. template: 'src/index.html'
  42. }), new CleanWebpackPlugin()],
  43. output: {
  44. // 加上前缀
  45. publicPath:'http://cdn.com.cn',
  46. filename: '[name].js',
  47. path: path.resolve(__dirname, 'dist')
  48. }
  49. }

我们会发现,当前的js都加上了刚刚的地址
image.png

知识补充

output
入口和上下文
管理输出
html-webpack-plugin