本人的项目是 Android、iOS app内部集成的H5页面,所有的路径需要相对路径,比如引用图片、引用js、引用css;
当前项目使用的多入口点,利用html-webpack-plugin自动注入。
大概配置如下:
var path = require('path')
var webpack = require('webpack')
var glob = require('glob');
var entries = getEntry('./src/module/**/*.js');
var HtmlWebpackPlugin = require('html-webpack-plugin');
module.exports = {
//entry: './src/main.js',
entry: entries,
output: {
path: path.resolve(__dirname, './dist'),
publicPath: '/',
filename: '[name].js'
},
module: {
rules: [
{
test: /\.vue$/,
loader: 'vue',
options: {
loaders: {
'scss': 'vue-style-loader!css-loader!sass-loader'
}
}
},
{
test: /\.js$/,
loader: 'babel',
exclude: /node_modules/
},
{
test: /\.(png|jpg|gif|svg)$/,
loader: 'file',
options: {
name: 'assets/image/[name].[ext]?[hash]'
}
},
{
test: /\.scss$/,
loader: ['style', 'css', 'resolve-url', 'sass']
},
{
test:/\.css$/,
loader:['style', 'css']
}
]
},
resolve: {
alias: {
'vue$': 'vue/dist/vue',
'pubscss':path.resolve(__dirname, 'src/assets/scss'),
'pubimg': path.resolve(__dirname, 'src/assets/image/public')
}
},
devServer: {
contentBase: path.join(__dirname, "dist/"),
historyApiFallback: true,
noInfo: true
},
devtool: '#eval-source-map',
plugins:[]
}
if (process.env.NODE_ENV === 'production') {
module.exports.devtool = '#source-map'
// http://vue-loader.vuejs.org/en/workflow/production.html
module.exports.plugins = (module.exports.plugins || []).concat([
new webpack.DefinePlugin({
'process.env': {
NODE_ENV: '"production"'
}
}),
new webpack.optimize.UglifyJsPlugin({
compress: {
warnings: false
}
}),
new webpack.LoaderOptionsPlugin({
minimize: true
})
])
}
//获取多页面的路径
function getEntry(globPath) {
var entries = {},
basename, tmp, pathname;
glob.sync(globPath).forEach(function (entry) {
basename = path.basename(entry, path.extname(entry)); //basename 为:detail
tmp = entry.split('/').splice(-3);
//pathname = tmp.splice(0, 1) + '\/' + basename; // 正确输出js和html的路径
pathname = tmp[0] + '\/' + tmp[1] + '\/' + basename; // modify by ls正确输出js和html的路径
entries[pathname] = entry;
});
console.log(entries);
return entries;
}
//add by ls 自动注入
var pages = getEntry('./src/module/**/*.html');
for (var pathname in pages) {
// 配置生成的html文件,定义路径等
var conf = {
filename: pathname + '.html',
template: pages[pathname],
chunks: [pathname, 'vendor', 'manifest'],
inject: true
};
module.exports.plugins.push(new HtmlWebpackPlugin(conf));
}
当前生成的 html 中js 的路径为:
<script type="text/javascript" src="/module/detail/detail.js"></script>
css中引用的图片路径为:
h1 {
background: transparent url(/assets/image/jingbao.png?1e0b744364551fe3f9ee92bf57bc9880) repeat scroll 0 0;
}
请问,如何能够生成相对路径的 ?? 改如何配置 webpack??
通过修改webpack配置里的output.publicPath为相对路径即可达到你的目的。
你现在的publicPath是'/',你先改成'./'来打包,这时候浏览器应该会报错的(路径出错),然后你就看着办来改相对路径呗。
详情可参考《webpack多页应用架构系列(二):webpack配置常用部分有哪些?》