【问题标题】:How to retrieve uncached versions of code splitting .js files using vue.js and webpack?如何使用 vue.js 和 webpack 检索代码拆分 .js 文件的未缓存版本?
【发布时间】:2021-07-22 01:53:11
【问题描述】:

所以,我在我的应用程序中安装了 Vue.js(使用 vue-cli 和 webpack)。一切都很好。此外,我已经实现了代码拆分,因此我不必加载在需要时才使用的组件。这一切都很好,也。但是,如果我要发布我的应用程序的新版本,则生成的代码拆分 .js 文件将缓存在客户端浏览器中,并且在清除浏览器中的缓存之前,它们不会获得更新.

为了防止在 main.js 之前发生这种情况,我实现了代码拆分,在 webpack 构建的 main.js 文件的查询字符串值中附加了版本号,如下所示:

<script src="~/scripts/build/main.js?v=@ViewBag.VersionNumber" asp-append-version="true"></script>

添加代码拆分后,我现在获得了 main.js 文件以及四个额外的 .js 文件,但我不确定如何对 main.js 文件引用的那些自动创建的 .js 文件进行版本控制。

main.js 0.js 1.js 2.js 3.js

我可以使用 webpack 中支持的魔法 cmets 轻松命名,如下所示:

const page0 = ()=> import(/* webpackChunkName: "my-page-0" */ './components/MyPage0.vue');
const page1 = ()=> import(/* webpackChunkName: "my-page-1" */ './components/MyPage1.vue');
const page2 = ()=> import(/* webpackChunkName: "my-page-2" */ './components/MyPage2.vue');
const page3 = ()=> import(/* webpackChunkName: "my-page-3" */ './components/MyPage3.vue');

但我不知道如何使名称动态化,以便我可以附加版本或哈希或其他会强制浏览器在进行软件更新后检索未缓存版本的内容。

【问题讨论】:

  • 看来你是在重新发明轮子。 Vue CLI 已经使用 HashedModuleIdsPlugin 来创建散列块。

标签: vue.js webpack code-splitting


【解决方案1】:

你必须使用 Webpack output 配置的 chunkFileName property。基本思想是在你的 Webpack 配置中读取package.json 文件并使用版本字段并将其附加到块名称。

const path = require('path');

// Assuming you have package.json. Read the version field.
const packageVersion = require('./package.json').version;

const SITE_DIST = path.join(__dirname, './dist');

module.exports = {
  output: {
    path: SITE_DIST,
    filename: '[name].[fullhash].bundle.js',

    // chunkFilename can be used to append the package version
    chunkFilename: `[name]-${packageVersion}.js`
  },
  // Other configuration....
}

附带说明,我不鼓励使用asp-append-version;尝试使用html-webpack-plugin 构建初始 HTML/ASP.NET 页面。 Webpack 为缓存破坏提供了更好的功能。您甚至可以生成一个 ASP 页面,同时确保将正确缓存的模块脚本/css 引用注入其中。例如,

new HtmlWebpackPlugin({
  template: './site/index.html',
  filename: 'index.asp'
})

为了生成唯一的文件名以避免缓存问题,您可以使用 Webpack 的内置输出生成 capabilities

filename: '[name].bundle.js',
filename: '[id].bundle.js',
filename: '[contenthash].bundle.js'
// Or any combination of above

此外,使用它,您甚至不需要使用您的项目版本。每次更改代码时,Webpack 都会使用 filenamechunkFilename 为您的包生成唯一名称;例如:main.f62606ed4879fe34afca.bundle.js。并且,这个名字会自动注入到插件生成的 HTML/ASP 文件中。

<script defer src="main.f62606ed4879fe34afca.bundle.js"></script>

【讨论】:

    猜你喜欢
    • 2019-08-13
    • 2017-07-13
    • 2017-08-07
    • 1970-01-01
    • 2020-01-30
    • 2023-03-12
    • 2020-09-14
    • 2020-08-12
    • 1970-01-01
    相关资源
    最近更新 更多