nuxt资源改为CDN地址-弯路经验更通用

2,143 阅读2分钟

nuxt资源改为CDN地址-弯路经验更通用

背景

目前项目使用nuxt并没有用上ssr特性,最终部署使用的是Jamstack架构。在nuxt版本v2.15前,是通过修改webpack中的output.publicPath属性来达到修改目的。在升级nuxt版本后,此设置失效。构建资源在页头中的预加载部分并没有生效。

<!- 页头预加载 ->
<link rel="preload" href="/_nuxt/vendor/253ae210.4ece1f28.js" as="script">

<!- 页脚资源 ->
<script src="//cdn.xxx.com/wap/vendor/253ae210.4ece1f28.js"></script>

解决过程

第一步,对比差异。对比线上最新配置文档,发现我手上配置并没有build.publicPath设置。

第二步,找到分歧点。通过查找版本信息来找到具体影响变动的版本,nuxt在v2.15版本增加了build.publicPathrouter.base 属性支持。

此 PR 允许在运行时配置 router.base 和 build.publicPath。在运行时,将评估这些值。路由器将被配置为反映新的 router.base,然后将使用正确的 publicPath(例如 CDN)更新注入的脚本,其中包括设置 webpack_public_path 以便构建的 JS 资产指向正确的位置。—— feat(config, vue-app, vue-renderer): support dynamic base and publicPath by danielroe · Pull Request #8520 · nuxt/nuxt.js (github.com)

export default {
  build: {
    publicPath: 'https://cdn.nuxtjs.org'
  }
}

所以结论是:

在v2.15版本后通过在build.publicPath设置cdn资源地址,构建时生产资源访问路径关系将已publicPath设置为准。最终满足资源部署至cdn的诉求。

弯路

选择解决办法的过程中脑抽了,认为build.publicPath这个设置不可用。然后跑去写shell脚本命令来替换生产出来的地址。用不上也记录一下XD

下面是替换脚本:

#!/bin/bash

set -e

path=$1
regExp='/_nuxt/'
cdnPath=$2

publicPath="$cdnPath/_nuxt/"

echo "替换CDN:$cdnPath"
echo "命中文件:"
grep "$regExp" -rl $path

sed -i "s@$regExp@$publicPath@g" `grep "$regExp" -rl $path`

命令的使用:

$ sh bin/repath.sh [目录地址] [CDN地址]

使用结果:

$ sh bin/repath.sh dist/ http://baidu.com
替换CDN:http://baidu.com
命中文件:
dist/200.html
dist/index.html
dist/_nuxt/app.ccd6f85a.css
dist/_nuxt/common.0e7c850c.css
dist/_nuxt/pages/foreign.434071aa.css
dist/_nuxt/pages/vip.d74fd1c5.css
dist/_nuxt/runtime.2d3c383f.js

在npm-scripts中使用:

{
	"scripts":{
		"build":"nuxt build --spa",
		"build:prod": "cross-env CDN_PATH=http://uxfeel.com npm run build",
		"build:test": "cross-env CDN_PATH=http://test.com npm run build",
		"postbuild": "cross-env-shell sh bin/repath.sh dist/ $CDN_PATH"
	}
}

小知识点

关于cross-env

  • cross-env 解决跨系统的变量设置问题。
  • cross-env 设置变量
  • cross-env-shell 应用变量

关于npm-scripts命令使用细节

{
  "scripts": {
    "precompress": "{{ 在`compress`命令前执行 }}",
    "compress": "{{ run command to compress files }}",
    "postcompress": "{{ 在`compress`命令后执行 }}"
  }
}