2019.12.27:新增「引用外部資源」段落。
本篇大綱
Nuxt.js用起來蠻順手的
前陣子看了一下Nuxt.js的文件後,實際拿了一個沒這麼急的案子來寫,覺得真的有順手。
這篇是筆記在看文件時,覺得未來會用到的,或是在開發過程中遇到的問題,然後研究一陣後找到的解法,作一個整理。
新增nuxt專案
開啟終端機,到想增加專案的資料夾中,輸入以下command:
npx create-nuxt-app 專案名稱
head的lang修改
nuxt專案生成的頁面,head會是en,如果想改變的話,在nuxt-config.js中的head寫入以下:
head: {
htmlAttrs: {
lang: 'zh-TW'
},
// ……
}
修改整頁使用的模版
在根目錄中,新增app.html,nuxt.js會去抓這個檔成為預設的模版。
例如,如果想把整頁加上IE hack的code,可以在app.html寫這樣:
<!DOCTYPE html>
<!--[if IE 9]><html lang="en-US" class="lt-ie9 ie9" {{ HTML_ATTRS }}><![endif]-->
<!--[if (gt IE 9)|!(IE)]><!--><html {{ HTML_ATTRS }}><!--<![endif]-->
<head {{ HEAD_ATTRS }}>
{{ HEAD }}
</head>
<body data {{ BODY_ATTRS }}>
{{ APP }}
</body>
</html>
用不同的layout
如果想要有多個模版,而不是像從頭到尾就一個模版到底,就先在layouts的資料夾建立一個新的layout檔,比方我們新增一個blog.vue,然後在想用這個新模版的*.vue中,寫入以下:
<template>
<!-- Your template -->
</template>
<script>
export default {
layout: 'blog'
}
</script>
引用外部資源
在上一篇「Nuxt.js 引用Firebase SDK」有人剛好詢問怎麼引用CDN,這邊也覺得有機會用到,就補充一下。
如果想要在頁面中引用外部資源,就在nuxt.configh.js的head中新增就行,像這樣:
head: {
script: [
{ src: 'https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js' }
],
link: [
{ rel: 'stylesheet', href: 'https://fonts.googleapis.com/css?family=Roboto&display=swap' }
]
}
使用sass、pug
話說,如果是用webpack打包檔案,為了能編譯sass、pug,還得花時間寫一些loader,久了沒用又會忘。
這是廣告,點擊一下可以幫本站多個一點點的廣告收入,謝謝
看到Nuxt.js只要用npm安裝後,就自動更新了config檔,不用在手寫loader就能立馬用,是很吸引Augustus用Nuxt.js的一點。
首先先安裝sass、pug的loader:
npm install --save-dev pug@2.0.3 pug-plain-loader node-sass sass-loader
然後…沒有然後了,就可以直接使用XD~
比方我們想在index.vue中使用:
<template lang="pug">
.container
p hello world
</template>
<style lang="sass">
.container
background: green
</style>
npm run generate到相對路徑
因為Augustus目前實際用的案子,是要直接產生靜態檔案,用FTP傳到主機上的,而且不是傳到根目錄中,是眾多資料夾的其中一個。
比方,我們最後要使用的網址為:
https://letswrite.tw/demo/blog/
那在nuxt.config.js的build中,就要改成以下:
router: {
base: '/demo/blog/'
},
build: {
extend (config, { isDev, isClient }) {
if (!isDev) {
config.output.publicPath = './_nuxt/'
}
return config;
}
}

