使用webpack打包工具,如何在打包后使得所有路径使用相对路径?

本人的项目是 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??

阅读 18.3k
3 个回答

第一步:修改webpack配置里的output.publicPath./

第二步:添加webpack配置里的devServer.publicPath/

之所以多了第二步,是对楼上回答的补充,如果不设置该选项,webpack-dev-server会无法正确的识别输出目录,浏览器访问会返回404错误
新手上路,请多包涵

第一步:修改webpack配置里的output.publicPath为./;
第二步:添加webpack配置里的devServer.publicPath为/;
第三步:修改serve.js中的devMiddleware 配置;将publicPath: webpackConfig.output.publicPath 的指向路径换成
publicPath:webpackConfig.devServer.publicPath。 具体如下:
var devMiddleware = require('webpack-dev-middleware')(compiler, {
noInfo: true,
publicPath:webpackConfig.devServer.publicPath
}) 即可操作成功

推荐问题
宣传栏