Reputation: 4076
I have a Vue.js project that is working fine in localhost.
But when I build and deploy to production, I need the static files (.css and .js) to be served on a "static" subdomain.
For example, my main URL:
https://www.example.com/index.html
The static assets will be:
https://static.example.com/css/app.50f83e17.css
https://static.example.com/js/chunk-vendors.6f495bf3.js
When I run "npm run build" Webpack build the "index.html" file loading like this:
<link href=/css/app.50f83e17.css rel=stylesheet>
But I need the href to be like this:
<link href=https://static.example.com/css/app.50f83e17.css rel=stylesheet>
How do I configure Vue.js or Webpack to build the "index.html" using a different subdomain for the CSS and JS?
Upvotes: 1
Views: 2524
Reputation: 496
To achieve this you would need to use webpack publicPath
You can configure webpack to build index.html using a different subdomain,
webpack.config.js
import webpack from 'webpack';
export default {
output: {
..
publicPath: 'https://static.example.com/js/',
},
};
npm run build Webpack build the "index.html" would have
..
..
<script type="text/javascript" src="https://static.example.com/js/chunk-vendors.6f495bf3.js"></script>
For 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',
],
},
],
},
};
You can also specify publicPath at runtime,
entry.js
__webpack_public_path__ = myRuntimePublicPath;
// rest of your application entry
Note: please consider adding a environment variable instead of hardcoding the asset CDN path, and pass the environment variable via npm scripts, alternately you can also define a global publicPath
var myRuntimePublicPath = 'https://static.example.com/js/'
and use it in the entry file (say entry.js) as displayed above.
refer: webpack publicPath and mini-css-extract-plugin publicPath
In case of using Vue Router
The base URL your application bundle will be deployed at publicPath (known as baseUrl before Vue CLI 3.3).
vue.config.js
module.exports = {
publicPath: process.env.NODE_ENV === 'production'
? 'https://static.example.com/js/'
: '/'
}
Vue Router
// override the base to hardcoded default value as it gets the value from publicPath
base: '/'
This will allow subdomain for javaScript bundle of vuejs build.
Upvotes: 3