本文共 2940 字,大约阅读时间需要 9 分钟。
html-webpack-plugin可以用html作为模版文件,但是这会和全局配置的html-loader冲突造成无法用ejs语法嵌入图片。
var path = require("path");var HtmlWebpackPlugin = require('html-webpack-plugin');const { CleanWebpackPlugin } = require('clean-webpack-plugin');const UglifyJsPlugin = require('uglifyjs-webpack-plugin')module.exports = { entry: { index: './src/index.js', demo: './src/demo.js', main: './src/main.js', }, output: { path: path.resolve(__dirname, './dist'), filename: 'js/[name].js', // publicPath:'http://cdn.com/', // 线上地址配置 }, mode: 'development', // devtool: "source-map", plugins: [ new CleanWebpackPlugin(),// 清除build文件 new HtmlWebpackPlugin({ chunks: ['main', 'index'], template: 'index.html', filename: 'index.html', }), new UglifyJsPlugin({ exclude: /\/main/ }),// new HtmlWebpackPlugin({ "files": { "css": ["./src/css/index.css", "./src/css/main.css"], }, date: new Date(), title: '自定义title', template: 'demo.html', filename: 'demo.html', favicon: './zft.ico', minify:{ removeRedundantAttributes:true, // 删除多余的属性 collapseWhitespace:true, // 折叠空白区域 removeAttributeQuotes: true, // 移除属性的引号 removeComments: true, // 移除注释 collapseBooleanAttributes: true // 省略只有 boolean 值的属性值 例如:readonly checked }, inject: true,// 是否自动引入js,css cache: false, hash: true, chunks: ['main', 'demo'], excludeChunks: ['index'] }), ], module: { rules: [ { test: /\.(png|jpg|gif)$/, use: [{ loader: 'url-loader', options: { esModule: false, // 这里设置为false } }], }, { test: /\.css$/, loader: "style-loader" }, { test: /\.css$/, loader: "css-loader" }, { test: /\.html$/, loader: 'html-loader' } ] },};
这是官方文档给出的解释:
解决方案:
方案一:去掉webpack.config.js文件中配置的全局html-loader(更方便,使用较多)
这样html模版文件就不会被html-loader解析,我们可以使用ejs语法嵌入其他html页面和图片资源。因为没了全局的html-loader解析html文件,使用ejs语法嵌入的资源返回的是ejs代码,还需要使用html-loader来解析成html代码。
(html-loader!)表示引用html-loader这个加载器来解析
<%= require('html-loader!../layout/left.html') %>
直接可以使用require来嵌入图片
/>
方案二:将模版文件全部替换成ejs文件(默认模版,官方推荐)
这样做的原因是即使使用了全局的html-loader来加载html文件,但是它也加载不到.ejs结尾的ejs文件。这样有效避免了html-loader对ejs fallback的影响。
因为有全局html-loader的存在,所以不需要加(html-loader!)前缀
<%= require('../layout/left.html') %> //如果嵌入文件是html文件
因为是ejs文件不会被全局html-loader加载,所以要加前缀
<%= require('html-loader!../layout/left.html') %> //如果嵌入文件是ejs文件
直接可以使用require来嵌入图片
/>
相关标签
转载地址:http://jead.baihongyu.com/