【问题标题】:Vue.js / Webpack build "index.html" using a "static" subdomain for CSS and JSVue.js / Webpack 使用 CSS 和 JS 的“静态”子域构建“index.html”
【发布时间】:2020-10-04 05:16:32
【问题描述】:

我有一个 Vue.js 项目在 localhost 中运行良好。

但是当我构建并部署到生产环境时,我需要在“静态”子域上提供静态文件(.css 和 .js)。

比如我的主网址:

https://www.example.com/index.html

静态资产将是:

https://static.example.com/css/app.50f83e17.css
https://static.example.com/js/chunk-vendors.6f495bf3.js

当我运行“npm run build”时,Webpack 构建“index.html”文件加载如下:

<link href=/css/app.50f83e17.css rel=stylesheet>

但我需要 href 是这样的:

<link href=https://static.example.com/css/app.50f83e17.css rel=stylesheet>

如何配置 Vue.js 或 Webpack 以使用 CSS 和 JS 的不同子域构建“index.html”?

【问题讨论】:

    标签: javascript vue.js webpack vue-cli


    【解决方案1】:

    要实现这一点,您需要使用 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 publicPathmini-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 包的子域。

    【讨论】:

    • 如果 OP 使用 Vue Router,他们需要确保 base 属性设置为 publicPath
    • 我用的是Vue Router,base属性是默认的'/'。
    • vue.config.js 的更新答案,请看这个答案:stackoverflow.com/a/59218186/3679048 在我看来,你可以做的是通过硬编码来保留 base 的默认值;根据: '/'。这样它就不会收到用于路由的 publicPath 值,并且您的资产文件仍会从所需的子域提供。
    猜你喜欢
    • 1970-01-01
    • 2017-08-16
    • 2014-11-08
    • 2018-10-02
    • 2019-01-05
    • 2017-08-20
    • 2019-04-09
    • 1970-01-01
    • 2017-06-15
    相关资源
    最近更新 更多