Parcel 與 Pug

2020-02-14 17:23 更新

Pug

支持?jǐn)U展類型: jade, pug

使用 Pug 很容易,這里提供幾個簡單的例子作為一點參考。

例 1 - Just index.pug

假設(shè)如下文件結(jié)構(gòu):

.
├── package.json
└── src
    └── index.pug

使用 Parcel 命令運行起來:parcel src/index.pug

例 2 - index.pug, index.js and style.css

假設(shè)如下文件結(jié)構(gòu):

.
├── package.json
└── src
    ├── index.js
    ├── index.pug
    └── style.css

在 index.pug 內(nèi),像往常一樣寫入樣式和 js。

// index.pug

doctype html
html(lang="")
  head
    // ...
    link(rel="stylesheet", href="index.css")
  body
    h1 Hello

    script(src="index.js")

以同樣的方式使用 Stylus, Sass or LESS,把樣式導(dǎo)入到 js 文件內(nèi)。

例 3 - Pug with locals

假設(shè)如下文件結(jié)構(gòu):

.
├── package.json
└── src
    ├── index.pug
    └── pug.config.js

我們需要從pug.config.js 文件導(dǎo)出 locals對象,pug.config.js文件必須放在 index.pug或者package.json文件所在目錄。

// pug.config.js

module.exports = {
  locals: {
    hello: 'world'
  }
}
// index.pug

doctype html
html(lang="")
  head
    // ...
  body
    h1 #{hello}

接著,使用命令運行起來:parcel src/index.pug

更新 locals 對象需要重新執(zhí)行 parcel

如果更新了locals對象,請關(guān)閉 parcel 進(jìn)程并重新執(zhí)行 parcel src/index.pug。

注意無聲的錯誤

當(dāng)使用 locals 設(shè)置時,在 Pug 中使用一個不存在的插值(interpolation)將不會收到任何錯誤告警。

假設(shè),我們寫了h1 #{thing}并且在 locals 對象中不存在thing 屬性,Parcel 不會暫停并報告任何錯誤。你只是在瀏覽器看到空的結(jié)果。因此,確保有一個正確的配置,否則插值(interpolation)不運行也不知道什么問題。

三種類型的配置文件

可以使用.pugrc 或 .pugrc.js來代替pug.config.js。但只有這三個文件可以設(shè)置 locals。

不能在 pug.config.js 文件中使用 import 語句

若要在pug.config.js中導(dǎo)入其他文件,請使用 require 語句。

// pug.config.js

const data = require('./data.js')

module.exports = {
  locals: {
    d: data
  }
}

添加腳本到 package.json

"scripts": {
    "dev": "parcel src/index.pug",
    "devopen": "parcel src/index.pug --open 'google chrome'",
    "build": "parcel build src/index.pug"
  },

使用npm run devopen自動打開瀏覽器,執(zhí)行npm run build生產(chǎn)環(huán)境打包。


以上內(nèi)容是否對您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號
微信公眾號

編程獅公眾號