Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

feat!: custom amp styles #206

Merged
merged 7 commits into from
Dec 12, 2020
Merged
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions docs/api/options.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ General options of amp module
| Option | Default | Valid values | Description |
| ------ | ------- | ------------ | ----------- |
| cdnBase | `https://cdn.ampproject.org/v0/` | Any String | A CDN Domain to load AMP elements scripts |
| css | `~/assets/style/amp-custom.css` | Path to CSS style | Custom styles for AMP pages |
| tags | `{}` | Object of tag options | Define new tags or modify current tags, for instance if you want to use `amp-mustache` version 0.1, tags value must be `{ 'amp-mustache': { version: '0.1' } }` |
| origin | `` | Any String | Main domain of website. Using this AMP modules tries to add missing canonical link for pages. |
| mode | `hybrid` | `only\|hybrid\|false` | Default behaviour of amp module. (`only` all pages serve in AMP mode by default, `hybrid` pages serves in both normal and AMP mode, `false` pages does not serve AMP by default ) |
Expand Down
3 changes: 3 additions & 0 deletions example/assets/styles/amp-custom.css
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
body {
background: #0cf;
}
3 changes: 0 additions & 3 deletions example/assets/styles/default.amp.css

This file was deleted.

File renamed without changes.
13 changes: 10 additions & 3 deletions example/nuxt.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,15 @@ module.exports = {
render: {
resourceHints: false
},
css: [
'~/assets/styles/default.scss'
],
build: {
extractCSS: true
},
modules: [
[ 'nuxt-i18n', {
locales: [ 'en', 'fr' ],
['nuxt-i18n', {
locales: ['en', 'fr'],
defaultLocale: 'en',
vueI18n: {
fallbackLocale: 'en',
Expand All @@ -22,10 +28,11 @@ module.exports = {
}
}
}
} ],
}],
{ handler: require('../') }
],
amp: {
css: '~/assets/styles/amp-custom.css',
origin: 'http://localhost:3000'
}
}
29 changes: 23 additions & 6 deletions lib/module.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,8 @@
const { readdirSync } = require('fs')
const { resolve, join } = require('path')
const consola = require('consola')
const chalk = require('chalk')
const { getTags, getNecessaryScripts } = require('./tags')

const logger = consola.withScope('@nuxtjs/amp')
const { logger, getAmpCustom, watchAmpCustom } = require('./utils')

const AMPBoilerplate = '<style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style><noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript>' +
'<script async src="https://cdn.ampproject.org/v0.js"></script>'
Expand All @@ -15,6 +13,7 @@ const ampBodyPattern = /<amp-body[^>]*>([.\S\s]*)<\/amp-body>/
module.exports = function (moduleOptions) {
const options = {
cdnBase: undefined,
css: '~/assets/styles/amp-custom.css',
origin: '',
mode: 'hybrid',
tags: {},
Expand All @@ -24,6 +23,17 @@ module.exports = function (moduleOptions) {
...moduleOptions
}

if (options.css) {
options.css = this.nuxt.resolver.resolveAlias(options.css)
options._fileWatcher = watchAmpCustom(options.css)
farnabaz marked this conversation as resolved.
Show resolved Hide resolved
this.nuxt.hook('close', () => {
if (options._fileWatcher) {
options._fileWatcher.close()
delete options._fileWatcher
}
})
}

registerPlugin.call(this, options)
copyAMP.call(this, options)
registerRendererHook.call(this, options)
Expand Down Expand Up @@ -142,9 +152,16 @@ function registerRendererHook (options) {

params.HEAD = params.HEAD
.replace(scriptPattern, v => (v.includes('custom-element') || v.includes('application/ld+json')) ? v : '')
.replace(/<\/style>\S*<style [^>]*>/g, '')
.replace(/<style/, '<style amp-custom')
.replace('@charset "UTF-8";', '')
/**
* Remove external styles
*/
.replace(/<style[^>]*>.*?<\/style>/g, '')
/**
* Remove external stylesheet
*/
.replace(/<link[^>]*rel="stylesheet".*>/gi, '')

params.HEAD += `<style amp-custom>${getAmpCustom(this.nuxt, options)}</style>`

params.HEAD += AMPBoilerplate

Expand Down
43 changes: 43 additions & 0 deletions lib/utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import fs from 'fs'
import chokidar from 'chokidar'
import consola from 'consola'

export const logger = consola.withScope('@nuxtjs/amp')

const ampCustom = {
farnabaz marked this conversation as resolved.
Show resolved Hide resolved
path: '',
content: ''
}
export function getAmpCustom (nuxt, options) {
if (!options.css) {
return ''
}
if (!ampCustom.path || ampCustom.path !== options.css) {
ampCustom.path = options.css
if (!fs.existsSync(ampCustom.path)) {
return ''
}
ampCustom.content = fs.readFileSync(ampCustom.path, { encoding: 'utf8' })
}
return ampCustom.content
}

export function clearAmpCustomCache () {
logger.info('Cache cleared')
ampCustom.path = ''
ampCustom.content = ''
}
export function watchAmpCustom (input) {
const filesWatcher = chokidar.watch(input, {
ignoreInitial: true
})

if (filesWatcher) {
logger.info('Watching for style changes')
filesWatcher.on('add', clearAmpCustomCache)
filesWatcher.on('change', clearAmpCustomCache)
filesWatcher.on('unlink', clearAmpCustomCache)
filesWatcher.on('unlinkDir', clearAmpCustomCache)
}
return filesWatcher
}
5 changes: 4 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@
"dependencies": {
"amphtml-validator": "^1.0.33",
"chalk": "^4.1.0",
"chokidar": "^3.4.3",
"consola": "^2.15.0"
},
"devDependencies": {
Expand All @@ -51,10 +52,12 @@
"husky": "^4.3.0",
"jest": "^26.6.3",
"jest-puppeteer": "^4.4.0",
"nuxt-edge": "^2.13.1-26548796.11a87d85",
"node-sass": "^5.0.0",
"nuxt-edge": "^2.14.8-26776834.e02fecdf",
"nuxt-i18n": "^6.15.4",
"puppeteer": "^5.5.0",
"request": "2.88.2",
"sass-loader": "^10.1.0",
"standard-version": "^9.0.0"
}
}
Loading