当前,当我执行yarn dev
时,我的包中以及dist目录的images
文件夹中都有图像。我的包和dist中的images
中也有相同的图像,这取决于图像的加载方式(<img src="*">
,<img ng-src="*">
)。
首先,我使用copy-webpack-plugin
复制了图像,但有些图像位于dist中的捆绑包和/或images
中(由于复制)。
我曾尝试使用file-loader
和url-loader
来加载此图像,但是我总是遇到无法正确加载图像的情况。
请注意我的文件树。
app / index.html
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.8/angular.min.js"></script>
</head>
<body>
<div ng-controller="Ctrl">
<div style="float: left">
<label style="display: block">Sun in src</label>
<img src="../images/sun.svg" width="200px">
</div>
<div style="float: left; margin-left: 100px">
<label style="display: block">Sun in ng-src</label>
<img ng-src="{{imgSun}}" width="200px">
</div>
<div style="float: left; margin-left: 100px">
<label style="display: block">Cloud in ng-src</label>
<img ng-src="{{imgCloud}}" width="200px">
</div>
</div>
</body>
</html>
app / app.js
angular.module("myApp", []).controller('Ctrl', function ($scope) {
$scope.imgSun = 'images/sun.svg';
$scope.imgCloud = 'images/cloud.svg';
});
webpack.config.js
const path = require('path');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const BrowserSyncPlugin = require('browser-sync-webpack-plugin');
const distDirectory = 'webpack-dist';
module.exports = {
mode: 'development',
bail: true,
entry: {'myApp': ['./app/index.html', './app/app.js']},
module: {
rules: [
{test: /\.svg$/, use: 'file-loader'},
/*{
test: /\.svg$/,
use: [{loader: 'file-loader', options: {name: '[path][name].[ext]?[hash]'}}],
include: path.resolve('images'),
},*/
//{test: /\.svg$/, use: 'url-loader', include: path.resolve('images')},
{test: /\.html$/, use: 'html-loader'},
]
},
watch: true,
plugins: [
new CleanWebpackPlugin(),
new HtmlWebpackPlugin({template: path.resolve('app/index.html')}),
new BrowserSyncPlugin({host: 'localhost', server: {baseDir: [path.resolve(distDirectory)]}})
],
output: {filename: '[name].bundle.js', path: path.resolve(distDirectory)}
};
package.json
{
"dependencies": {
"browser-sync": "^2.26.3",
"browser-sync-webpack-plugin": "^2.2.2",
"clean-webpack-plugin": "^2.0.1",
"file-loader": "^3.0.1",
"html-loader": "^0.5.5",
"html-webpack-plugin": "^3.2.0",
"url-loader": "^1.1.2",
"webpack": "^4.29.6",
"webpack-cli": "^3.3.0"
},
"scripts": {
"dev": "node_modules/.bin/webpack --open"
}
}
我想将所有图像都放在包装中。
我不想在dist中复制数据(捆绑和images
文件夹)。
因此,我将能够将[hash]
添加到我的捆绑软件中,而浏览器缓存也不再存在问题。