Webpack4.x 解决本地和生产地址不一致,使用绝对地址

依赖关系:

"webpack": "^4.12.0",

"webpack-cli": "^3.0.3",

"vue": "^2.5.16",

"vue-loader": "^14.2.2",

Webpack配置output内容:参考

// :关键点:
const publicPath = isProd ? '/vue/' : '/';

output: {
  path: path.resolve('dist' + publicPath),
  publicPath: publicPath,
  filename: `js/[name]${isProd ? '.[hash:7]' : ''}.js`
},

// 关键点: 上面的publicPath相当于Webpack 的 DefinePlugin执行了↓
new webpack.DefinePlugin({
  'process.env.ASSET_PATH': JSON.stringify(extPath),
}),

Vue组件A标签使用href路径:

// 测试环境路径为: /tools

// 生产环境路径为: /vue/tools

<a :href="`${__webpack_public_path__}tools/fifa`">
const link = `${__webpack_public_path__}tools/fifa`

相关推荐