webpack.condig.js:

const path = require('path'); //導入插件 const VueLoaderPlugin = require('vue-loader/lib/plugin');//加這句是為了避免報錯:Module Error (from ./node_modules/vue-loader/lib/index.js): const MiniCssExtractPlugin = require('mini-css-extract-plugin'); module.exports={ entry:{ main:'./main' }, output:{ path:path.join(__dirname,'./dist'), publicPath:'/dist/', filename:'main.js' }, module:{ rules:[ { test:/\.vue$/, loader:'vue-loader', options:{ loaders:{ css:MiniCssExtractPlugin.loader } } }, { test:/\.js$/, loader:'babel-loader', exclude:/node_modules/ }, { test: /\.css$/, use: [MiniCssExtractPlugin.loader, 'css-loader'], }, // { // test: /\.(htm|html)$/i, // use:[ 'html-withimg-loader'] // }, { test: /\.(png|jpg|gif|bmp|jpeg|svg)$/, use: [ { loader: 'url-loader', options:{ limit:1024,//限制打包圖片的大小: } }, ], }, ] }, plugins:[ new VueLoaderPlugin(), new MiniCssExtractPlugin({ filename: '[name].css', }), ] }
webpack.config.prod.js:

//導入插件 const VueLoaderPlugin = require('vue-loader/lib/plugin');//加這句是為了避免報錯:Module Error (from ./node_modules/vue-loader/lib/index.js): const webpack= require('webpack'); const HtmlWebpackPlugin = require('html-webpack-plugin') const MiniCssExtractPlugin = require('mini-css-extract-plugin'); const UglifyJsPlugin = require('uglifyjs-webpack-plugin');//用來對js文件進行壓縮,從而減小js文件的大小,加速load速度 const merge=require('webpack-merge'); const webpackBaseConfig=require('./webpack.config.js'); //清空基本配置的插件列表 webpackBaseConfig.plugins=[]; module.exports=merge(webpackBaseConfig,{ output:{ publicPath:'./dist/',// /dist/前面要加一個.,這樣才能找到css、js和圖片的位置 //'[name].[hash].js' 將入口文件重命名為帶有20位hash值的唯一文件 filename: '[name].js' }, plugins:[ new VueLoaderPlugin(), new MiniCssExtractPlugin({ filename: '[name].css', chunkFilename: '[id].css', }), new webpack.DefinePlugin({ 'process.env':{ NODE_ENV:'"production"' } }), //提取模板,並保存入口html文件 new HtmlWebpackPlugin({ title: 'Custom template', filename:'../index_prod.html', // template: 'html-withimg-loader!'+'./index.ejs', // Load a custom template (lodash by default see the FAQ for details) template: './index.ejs', inject:true }) ], optimization: { minimizer: [new UglifyJsPlugin()], }, } )
index.ejs:
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-type" content="text/html; charset=utf-8"/> <title><%= htmlWebpackPlugin.options.title %></title> </head> <body> <div id="app"> </div> <img src="./images/cmmn.jpg" style="width: 200px"/> style="width: 200px"/> </body> </html>
在html-webpack-plugin配置中的模板文件(如html或者ejs文件)中直接通過img標簽的src屬性引入圖片路徑,結果圖片是不會被打包的,但是編譯也不報錯。
(奇怪的是在.vue文件中使用src直接引用路徑就沒問題)
網上有人提出可以安裝html-withimg-loader插件,並配置對應的信息,就可以打包成功了。這么做確實會使得圖片打包成功,但是會有一個問題,即webpack.config.prod.js文件中的HtmlWebpackPlugin中的title不會被編譯到index.ejs(這個問題是因為使用html-withimg-loader后,正則表達式中被匹配到的文件中的<%= %> 會直接被當做字符串原樣輸出,而不會被編譯)。
目前,正確的做法是,在模板文件中,img標簽在引入src路徑時,通過require的方式引入,即:
<img src="<%= require('./images/cmmn.jpg')%>" style="width: 200px"/>
然后運行命令 npm run build 就可以看到被打包的信息了