Nuxt.js如何为_nuxt目录生成的静态资源设置自定义路径前缀
问题根因
你当前配置失效的核心原因是nuxt.config.js中存在重复的build配置项:文件前半段你声明了带publicPath的build配置,但是文件末尾又定义了一个空的build: {},后者会直接覆盖前者的配置,导致publicPath完全没有生效。
正确配置步骤
- 合并重复的build配置,修正publicPath写法
Nuxt2默认编译后的资源路径为/_nuxt/,要实现/customprefix/_nuxt/的访问路径,publicPath需要完整配置前缀+默认资源目录,同时注意结尾要加斜杠。 - 添加路由基础路径配置(按需)
如果你的整个Nuxt应用都部署在/customprefix子路径下,需要同时配置router.base,保证页面路由、静态资源路径都自动带前缀。 - 修正静态资源引用路径
头部的favicon等静态资源路径需要同步加上前缀,或者使用相对路径引用避免硬编码。 - 不需要手动在项目根目录创建
customprefix文件夹,执行nuxt build后会自动在dist目录生成对应层级的资源目录,直接部署dist内容到服务器对应路径即可。
修改后的完整配置
export default { // Global page headers: https://go.nuxtjs.dev/config-head router: { base: '/customprefix/' }, static:{ prefix: true }, head: { titleTemplate: '%s - nuxt-test', title: 'nuxt-test', htmlAttrs: { lang: 'en' }, meta: [ { charset: 'utf-8' }, { name: 'viewport', content: 'width=device-width, initial-scale=1' }, { hid: 'description', name: 'description', content: '' }, { name: 'format-detection', content: 'telephone=no' } ], link: [ { rel: 'icon', type: 'image/x-icon', href: '/customprefix/favicon.ico' } ] }, // Global CSS: https://go.nuxtjs.dev/config-css css: [ ], // Plugins to run before rendering page: https://go.nuxtjs.dev/config-plugins plugins: [ ], // Auto import components: https://go.nuxtjs.dev/config-components components: true, // Modules for dev and build (recommended): https://go.nuxtjs.dev/config-modules buildModules: [ '@nuxtjs/vuetify', ], // Modules: https://go.nuxtjs.dev/config-modules modules: [ ], // Vuetify module configuration: https://go.nuxtjs.dev/config-vuetify vuetify: { customVariables: ['~/assets/variables.scss'], theme: { dark: true, themes: { dark: { primary: colors.blue.darken2, accent: colors.grey.darken3, secondary: colors.amber.darken3, info: colors.teal.lighten1, warning: colors.amber.base, error: colors.deepOrange.accent4, success: colors.green.accent3 } } } }, // Build Configuration: https://go.nuxtjs.dev/config-build build: { publicPath: '/customprefix/_nuxt/' } }
配置修改完成后重新执行nuxt build打包即可生效。
内容的提问来源于stack exchange,提问作者Satria Janaka
相关产品推荐
相关产品推荐

