`

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`
// Property or method "__webpack_public_path__" is not defined on the instance but referenced during render
需要注册__webpack_public_path__给vue的data
data () {
  this.__webpack_public_path__ = __webpack_public_path__
  return {
    ...
  }
}

  

 

解决:保证开发和生产环境路径一致

 

 

图片路径问题:

{
  test: /\.(jpe?g|png|gif|svg)$/,
  use: [
    {
      loader: 'url-loader',
      options: {
        fallback: 'file-loader',
        limit: 10000,
        // 设置导出路径,相对于output的publicPath路径
        outputPath: 'images/'
      }
    }
  ]
},

 

生产打包tree:

└── vue

    ├── favicon.ico

    ├── images

    │   ├── 1cb4d60d80d9ed007efb9f9d2f934a00.png

    │   └── 81f5b003430bdd08ee0ad4df21c3acf6.png

    ├── index

    │   └── index.html

    ├── js

    │   ├── 0.d0b19b9.js.gz

    │   ├── 1.d0b19b9.js.gz

    │   ├── fifa

    │   │   └── 2018.d0b19b9.js.gz

    │   ├── index.d0b19b9.js.gz

    │   ├── social

    │   │   └── photo.d0b19b9.js.gz

    │   └── tools

    │       ├── fifa.d0b19b9.js.gz

    │       ├── flag-logo

    │       │   └── all.d0b19b9.js.gz

    │       └── vscode.d0b19b9.js.gz

    └── tools

        ├── fifa

        │   └── index.html

        ├── flag-logo

        │   ├── all

        │   │   └── index.html

        │   └── index.html

        └──   

 

更多访问:github: https://github.com/qiaolevip

            or   coding

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics