环境配置文件:

// dev.env.js
'use strict'

module.exports = {
    CDN_PATH: '"http://statictest.ucarinc.com/"'
}
// prod.env.js
'use strict'

module.exports = {
    CDN_PATH: '"https://inner.10101111cdn.com/"'
}

生产环境webpack:

// webpack.dev.conf.js
const env = require('../config/dev.env')
module.exports = {
    entry: {},
    output: {},
    resolve: {},
    externals: {},
    module: {},
    plugins: [
        new HtmlWebpackPlugin({
          base_home: env.CDN_PATH.replace(/^\"|\"$/g, ''),
          // coding
        }),
    ]
}

生产环境:

// webpack.prod.conf.js
const env = require('../config/prod.env')
module.exports = {
    entry: {},
    output: {},
    resolve: {},
    externals: {},
    module: {},
    plugins: [
        new HtmlWebpackPlugin({
          base_home: env.CDN_PATH.replace(/^\"|\"$/g, ''),
          // coding
        }),
    ]
}

index.html模板中更改请求域名

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width,initial-scale=1.0">
  <meta name="format-detection" content="telephone=no">
  <title>采购管理系统</title>
  <link rel="stylesheet" href="<%= htmlWebpackPlugin.options.base_home%>??static/ucar-view-2.0.6.css" />
</head>
<body>
  <div id="app"></div>
    <!-- built files will be auto injected -->
    <script src="<%= htmlWebpackPlugin.options.base_home%>??static/ucar-view.umd.min-2.0.6.js"></script>
    </script>
  </body>
</html>

以上有几点需要注意
1、dev.env.js或者prod.env.js文件中定义CDN_PATH变量需要同时加上单引号和双引号,不然会报错
2、但是CDN_PATH加上双引号之后,htmlWebpackPlugin.options.base_home值为"http://statictest.ucarinc.com/",在script使用就会变成<script src=""http://statictest.ucarinc.com/"??static/ucar-view.umd.min-2.0.6.js"></script>,这个链接是有问题的,解决方法是在HtmlWebpackPlugin插件中定义是去掉双引号base_home: env.CDN_PATH.replace(/^\"|\"$/g, '')


记得要微笑
1.9k 声望4.5k 粉丝

知不足而奋进,望远山而前行,卯足劲,不减热爱。