嗨,我正在尝试创建一个Webpack配置,该配置为该项目内的每个文件夹生成文件。 不是不是为每个文件夹创建webpack.config。
我有一个index.html,JS和SASS已全部处理。下一步是图像,我正在努力。
当前发生的是:
name: '[path]../../dist/img/[name].[ext]'
在此文件夹中,有“模块”,每个模块都是一个文件夹。
源代码:
/MyProject/MyModule/src/js/app.js
/MyProject/MyModule/src/scss/app.scss
/MyProject/MyModule/src/index.html
/MyProject/MyModule/src/img/example1.jpg
dist:
MyProject / MyModule / dist /(app.css | app.js | index.html | img / example1.jpg)
我的问题
保存图像时,采用下面的当前方式,
<img src="/MyModule/src/img/../dist/img/screenshot.png" alt="Screenshot">
我的HTML输出是这样的:
[path]
我愿意了解为什么,但是我不知道有什么更好的方法。
如果我删除const entryPlus = require('webpack-entry-plus');
const glob = require('glob');
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const fs = require('fs');
const htmlList_exclusions = [
'node_modules'
]
const htmlList = []
const imgList = []
const files = fs.readdirSync(__dirname)
files.forEach(file => {
var filePath = path.join(__dirname, file);
var isDir = fs.statSync(filePath).isDirectory();
if(isDir && !file.startsWith('.') && !file.startsWith('_') && !htmlList_exclusions.includes(file)) {
htmlList.push(filePath + '/src/index.html')
}
});
const entryFiles = [
{
entryFiles: glob.sync('./*/src/js/app.js'),
outputName(item) {
return item.replace('src/js/', 'dist/').replace('.js', '').replace('./', '');
},
},
];
const plugins = [
new MiniCssExtractPlugin({
// Options similar to the same options in webpackOptions.output
// both options are optional
// path: '[folder]tes',
filename: '[name].css',
})
]
for(var i in htmlList) {
plugins.push( new HtmlWebpackPlugin({
template: htmlList[i],
filename: htmlList[i].replace('src/', '/'),
}));
}
module.exports = {
watch: true,
entry: entryPlus(entryFiles),
output: {
path: path.resolve(__dirname, './'),
filename: '[name].js',
publicPath: '/',
},
module: {
rules: [
{
test: /\.(sa|sc|c)ss$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
// you can specify a publicPath here
// by default it use publicPath in webpackOptions.output
// publicPath: '../',
sourceMap: false,
}
},
"css-loader", "sass-loader"
]
},
{
test: /\.js$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env'],
plugins: ['@babel/plugin-proposal-object-rest-spread', '@babel/plugin-transform-runtime']
}
}
},
{
test: /\.html$/,
use: ['html-loader'],
},
{
test: /\.(jpg|png|gif)$/,
use: [
{
loader: 'file-loader',
options: {
name: '[path]../dist/img/[name].[ext]',
outputPath: '',
publicPath: '/',
}
}
]
}
]
},
plugins,
resolve: {
alias: {
globalscss: path.resolve(__dirname, './_global/scss/'),
}
}
}
,它当然会保存在MyProject而不是MyModule里面,这是我不想要的。
webpack.config.js
{{1}}
答案 0 :(得分:0)
我将为更好的RegExp工作,但是我使用了以下解决方案
{
test: /\.(jpg|png|gif|svg)$/,
use: [
{
loader: 'file-loader',
options: {
regExp: /([^\0]+)\/([^\0]+)\/([^\0]+)\/([^\0]+)\/([^\0]+)\.(jpg|png|gif|svg)$/,
name: '[2]/dist/img/[name].[ext]',
outputPath: '',
publicPath: '/',
}
}
]
}