当我想将 nuxt 项目部署到 github 页面时遇到一些麻烦。
我已经在public文件夹下添加了
.nojekyll
文件,但是运行generate后,带“_”的文件仍然出现在public/static下。 package.json
"scripts": {
"build": "nuxt build",
"dev": "nuxt dev",
"generate": "nuxt generate",
"preview": "nuxt preview",
"postinstall": "nuxt prepare"
},
"devDependencies": {
"@nuxtjs/google-adsense": "^3.0.0",
"@nuxtjs/google-fonts": "^3.0.0",
"@nuxtjs/tailwindcss": "^6.10.4",
"autoprefixer": "^10.4.16",
"nuxt": "^3.9.1",
"nuxt-simple-sitemap": "^3.2.5",
"postcss": "^8.4.33",
"tailwindcss": "^3.4.1",
"vue": "^3.4.10",
"vue-router": "^4.2.5"
},
"dependencies": {
"@nuxtjs/robots": "^3.0.0",
"@pinia/nuxt": "^0.5.1",
"nuxt-jsonld": "^2.0.8",
"pinia": "^2.1.7"
}
nuxt.config.ts
我不需要设置 baseUrl 因为我已经有重定向了。
experimental: {
payloadExtraction: false,
},
app: {
buildAssetsDir: "/static/",
},
nitro: {
preset: "github-pages",
},
devServer: {
port: 3000,
},
devtools: { enabled: true },
modules: [
"@pinia/nuxt",
"@vueuse/nuxt",
"nuxt-simple-sitemap",
"@nuxtjs/robots",
"nuxt-jsonld",
"@nuxtjs/tailwindcss",
[
"@nuxtjs/google-fonts",
{
families: {
"Noto+Sans+TC": [500, 700],
Roboto: [500, 700],
},
display: "swap",
download: true,
overwriting: false,
inject: true,
preload: true,
},
],
],
仍然会生成
_plugin-vue_export-helper.x3n3nnut.js
和_name_.LPWOZD9u.js
这两个文件,导致我部署到github页面后网站无法正常运行我解决了这个问题。
我发现nuxt3是使用vite构建的。
我将以下代码添加到
nuxt.config.ts
const INVALID_CHAR_REGEX = /[\x00-\x1F\x7F<>*#"{}|^[\]`;?:&=+$,]/g;
const DRIVE_LETTER_REGEX = /^[a-z]:/i;
export default defineNuxtConfig({
vite: {
build: {
rollupOptions: {
output: {
// https://github.com/rollup/rollup/blob/master/src/utils/sanitizeFileName.ts
sanitizeFileName(name) {
const match = DRIVE_LETTER_REGEX.exec(name);
const driveLetter = match ? match[0] : "";
return (
driveLetter +
name.slice(driveLetter.length).replace(INVALID_CHAR_REGEX, "")
);
},
},
},
},
},
...
})
再次运行
npm run generate
后,public文件夹下将不再出现带“_”的文件或文件夹,可以正确部署到github页面了。