要实现这一点,您需要使用 webpack publicPath
您可以配置 webpack 以使用不同的子域构建 index.html,
webpack.config.js
import webpack from 'webpack';
export default {
output: {
..
publicPath: 'https://static.example.com/js/',
},
};
npm run build Webpack 构建“index.html”将有
..
..
<script type="text/javascript" src="https://static.example.com/js/chunk-vendors.6f495bf3.js"></script>
对于css,
webpack.config.js
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
module.exports = {
plugins: [
new MiniCssExtractPlugin({
filename: '[name].css',
chunkFilename: '[id].css',
}),
],
module: {
rules: [
{
test: /\.css$/,
use: [
{
loader: MiniCssExtractPlugin.loader,
options: {
publicPath: 'https://static.example.com/css/',
},
},
'css-loader',
],
},
],
},
};
也可以在运行时指定publicPath,
entry.js
__webpack_public_path__ = myRuntimePublicPath;
// rest of your application entry
注意:请考虑添加环境变量而不是硬编码资产CDN路径,并通过npm脚本传递环境变量,或者您也可以定义全局publicPath
var myRuntimePublicPath = 'https://static.example.com/js/'
并在上面显示的入口文件(比如entry.js)中使用它。
参考:webpack publicPath 和 mini-css-extract-plugin publicPath
如果使用 Vue Router
您的应用程序包将部署在 publicPath 的基本 URL(在 Vue CLI 3.3 之前称为 baseUrl)。
vue.config.js
module.exports = {
publicPath: process.env.NODE_ENV === 'production'
? 'https://static.example.com/js/'
: '/'
}
Vue 路由器
// 在从 publicPath 获取值时,将基础覆盖为硬编码的默认值
base: '/'
这将允许 vuejs 构建的 javaScript 包的子域。