Webpack正在将我的图像从src
文件夹移动到built
文件夹。当我使用任务运行器或npm run-script dev
运行Development
时,我可以看到的图像从src移到了我的built文件夹。我遇到的问题是,每当我对CSS或HTML进行更改时,我确实会收到一个成功的构建,但图像随后会从built
文件夹中删除,因此无法加载。
很多文章,包括this上关于S.O的文章,告诉我我需要使用‘复制-webpack-插件’,还有file-loader
,但我有这些。
const CopyWebpackPlugin = require('copy-webpack-plugin');
我的条目文件如下所示
module.exports = {
entry: {
app: './src/main.js'
},
output: {
path: path.resolve(__dirname, './built'),
publicPath: '/built'
},
optimization: {
minimizer: [
new UglifyJsPlugin({
cache: true,
parallel: true,
sourceMap: false // set to true if you want JS source maps
}),
new OptimizeCSSAssetsPlugin()
]
},
plugins: [
// Clean built folder.
new CleanWebpackPlugin({
"verbose": true // Write logs to console.
}),
// avoid publishing when compilation failed.
new webpack.NoEmitOnErrorsPlugin(),
// Move & compress/process images
new CopyWebpackPlugin(
[
{
from: path.resolve(__dirname, './src/img/'),
to: path.resolve(__dirname, './built/img/')
},
{
from: path.resolve(__dirname, './src/fonts/'),
to: path.resolve(__dirname, './built/fonts/')
},
]),
new ImageminPlugin({
test: /\.(jpe?g|png|gif|svg)$/i,
pngquant: {
quality: '95-100'
}
}),
new HtmlWebpackPlugin({
inject: "body",
filename: "../Views/Shared/_Layout.cshtml",
template: "./Views/Shared/_Layout_Template.cshtml"
}),
new WebpackNotifierPlugin(),
],
module: {
rules: [
{
// Enable ES6 transpilation
test: /\.js$/,
exclude: /node_modules/,
use: ['babel-loader', 'eslint-loader']
},
{
test: /\.((s)?css)$/,
use: [
{ loader: "style-loader" },
{
loader: MiniCssExtractPlugin.loader
},
{
// Interprets `@import` and `url()` like `import/require()` and will resolve them
loader: 'css-loader'
},
{
// Loader for webpack to process CSS with PostCSS
loader: 'postcss-loader',
options: {
plugins: function () {
return [
require('autoprefixer')
];
},
}
},
{
loader: 'resolve-url-loader'
},
{
// Loads a SASS/SCSS file and compiles it to CSS
loader: 'sass-loader',
options: {
sourceMap: true,
sourceMapContents: false
}
}
]
},
// Font files will be handled here
{
test: /\.(woff|woff2|eot|ttf|otf)$/,
use: [{
loader: 'file-loader'
}]
},
// Image files will be handled here
{
test: /\.(jpg|png|gif|svg)$/,
use: [{
loader: 'file-loader'
}]
},
// All files with ".html" will be handled
{ test: /\.html$/, loader: "html-loader" }
]
},
};
正如我所说的,我不明白的是,为什么当我第一次运行脚本时,我会得到一个“构建成功”,但是当我做了更改,然后Webpack变魔术时,图像就会从我的built
文件夹中删除。
我像这样引用我的文件
<img src="/built/img/example.png">
发布于 2019-03-21 06:51:01
尝试设置copyUnmodified选项。看起来在手表模式下的CleanWebpackPlugin
会在每次更新时清理所有内容,但是CopyWebpackPlugin
不会再复制这些文件。
new CopyWebpackPlugin(
[
{
from: path.resolve(__dirname, './src/img/'),
to: path.resolve(__dirname, './built/img/')
},
{
from: path.resolve(__dirname, './src/fonts/'),
to: path.resolve(__dirname, './built/fonts/')
},
], {
copyUnmodified: true
}),
https://stackoverflow.com/questions/55271138
复制相似问题