Skip to content

feat: free to name markdown files #439

New issue

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

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

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all 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
4 changes: 1 addition & 3 deletions lib/app/Content.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import { pathToComponentName } from './util'

export default {
functional: true,

Expand All @@ -11,7 +9,7 @@ export default {
},

render (h, { parent, props, data }) {
return h(pathToComponentName(parent.$page.path), {
return h(parent.$page.name, {
class: [props.custom ? 'custom' : '', data.class, data.staticClass],
style: data.style
})
Expand Down
9 changes: 1 addition & 8 deletions lib/app/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,8 @@ export function injectMixins (options, mixins) {
options.mixins.push(...mixins)
}

export function pathToComponentName (path) {
if (path.charAt(path.length - 1) === '/') {
return `page${path.replace(/\//g, '-') + 'index'}`
} else {
return `page${path.replace(/\//g, '-').replace(/\.html$/, '')}`
}
}

export function findPageForPath (pages, path) {
path = decodeURIComponent(path)
for (let i = 0; i < pages.length; i++) {
const page = pages[i]
if (page.path === path) {
Expand Down
3 changes: 1 addition & 2 deletions lib/default-theme/Layout.vue
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,6 @@ import Home from './Home.vue'
import Navbar from './Navbar.vue'
import Page from './Page.vue'
import Sidebar from './Sidebar.vue'
import { pathToComponentName } from '@app/util'
import store from '@app/store'
import { resolveSidebarItems } from './util'
import throttle from 'lodash.throttle'
Expand Down Expand Up @@ -94,7 +93,7 @@ export default {
nprogress.configure({ showSpinner: false })

this.$router.beforeEach((to, from, next) => {
if (to.path !== from.path && !Vue.component(pathToComponentName(to.path))) {
if (to.path !== from.path && !Vue.component(to.name)) {
nprogress.start()
}
next()
Expand Down
4 changes: 2 additions & 2 deletions lib/default-theme/SidebarLink.vue
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
<script>
import { isActive, hashRE, groupHeaders } from './util'
import { isActive, hashRE, groupHeaders, getUrlSafePath } from './util'

export default {
functional: true,
Expand Down Expand Up @@ -32,7 +32,7 @@ export default {
function renderLink (h, to, text, active) {
return h('router-link', {
props: {
to,
to: getUrlSafePath(to),
activeClass: '',
exactActiveClass: ''
},
Expand Down
4 changes: 4 additions & 0 deletions lib/default-theme/util.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,9 @@ export const extRE = /\.(md|html)$/
export const endingSlashRE = /\/$/
export const outboundRE = /^(https?:|mailto:|tel:)/

import { getUrlSafePath } from '../util/shared'
export { getUrlSafePath }

export function normalize (path) {
return path
.replace(hashRE, '')
Expand Down Expand Up @@ -43,6 +46,7 @@ export function ensureExt (path) {
}

export function isActive (route, path) {
path = getUrlSafePath(path)
const routeHash = route.hash
const linkHash = getHash(path)
if (linkHash && routeHash !== linkHash) {
Expand Down
18 changes: 18 additions & 0 deletions lib/dev.js
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,15 @@ module.exports = async function dev (sourceDir, cliOptions = {}) {
// resolve webpack config
let config = createClientConfig(options, cliOptions)

// virtual-modules
let virtualModules
config.plugin('virtual-modules').init(
(Plugin, args) => {
virtualModules = new Plugin(...args)
return virtualModules
}
)

config
.plugin('html')
// using a fork of html-webpack-plugin to avoid it requiring webpack
Expand Down Expand Up @@ -84,6 +93,15 @@ module.exports = async function dev (sourceDir, cliOptions = {}) {
portfinder.basePort = cliOptions.port || options.siteConfig.port || 8080
const port = await portfinder.getPortPromise()

// virtual-modules
compiler.hooks.watchRun.tap('vuepress', () => {
delete require.cache[require.resolve('./app/.temp/pageContent')]
const pageContent = require('./app/.temp/pageContent')
Object.keys(pageContent).forEach(pagePath => {
virtualModules.writeModule(pagePath, pageContent[pagePath])
})
})

let isFirst = true
compiler.hooks.done.tap('vuepress', () => {
if (isFirst) {
Expand Down
40 changes: 32 additions & 8 deletions lib/prepare.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,9 @@ const {
inferTitle,
extractHeaders,
parseFrontmatter,
getGitLastUpdatedTimeStamp
getGitLastUpdatedTimeStamp,
getUrlSafePath,
getPageComponentName
} = require('./util')

fs.ensureDirSync(tempPath)
Expand Down Expand Up @@ -71,6 +73,16 @@ if (!Object.assign) Object.assign = require('object-assign')`
// 7. handle the theme enhanceApp.js
await writeEnhanceTemp('themeEnhanceApp.js', options.themeEnhanceAppPath)

// 8. generate page content
const pageContent = options.siteData.pages.reduce(
(pageContent, { name: componentName, filepath, content }) => {
pageContent[pageFilePathToVirtualPath(filepath, componentName)] = content
return pageContent
},
{}
)
writeTemp('pageContent.js', `module.exports = ${JSON.stringify(pageContent)}`)

return options
}

Expand Down Expand Up @@ -204,8 +216,14 @@ async function resolveOptions (sourceDir) {
data.lastUpdated = getGitLastUpdatedTimeStamp(filepath)
}

// extract yaml frontmatter
const content = await fs.readFile(filepath, 'utf-8')
Object.defineProperty(data, 'filepath', { value: filepath })
Object.defineProperty(data, 'content', { value: content })

// get page component name
data.name = getPageComponentName(data.path)

// extract yaml frontmatter
const frontmatter = parseFrontmatter(content)
// infer title
const title = inferTitle(frontmatter)
Expand Down Expand Up @@ -297,6 +315,11 @@ function fileToComponentName (file) {
return `${pagePrefix}${normalizedName}`
}

function pageFilePathToVirtualPath (filepath, componentName) {
const { dir, ext } = path.parse(filepath)
return path.join(dir, `__${componentName}__${ext}`)
}

function isIndexFile (file) {
return indexRE.test(file)
}
Expand All @@ -310,16 +333,17 @@ async function resolveComponents (sourceDir) {
}

async function genRoutesFile ({ siteData: { pages }, sourceDir, pageFiles }) {
function genRoute ({ path: pagePath }, index) {
function genRoute ({ path: pagePath, content, name: componentName }, index) {
const file = pageFiles[index]
const filePath = path.resolve(sourceDir, file)
let code = `
{
path: ${JSON.stringify(pagePath)},
name: ${JSON.stringify(componentName)},
path: ${JSON.stringify(getUrlSafePath(pagePath))},
component: ThemeLayout,
beforeEnter: (to, from, next) => {
import(${JSON.stringify(filePath)}).then(comp => {
Vue.component(${JSON.stringify(fileToComponentName(file))}, comp.default)
import(${JSON.stringify(pageFilePathToVirtualPath(filePath, componentName))}).then(comp => {
Vue.component(${JSON.stringify(componentName)}, comp.default)
next()
})
}
Expand All @@ -328,8 +352,8 @@ async function genRoutesFile ({ siteData: { pages }, sourceDir, pageFiles }) {
if (/\/$/.test(pagePath)) {
code += `,
{
path: ${JSON.stringify(pagePath + 'index.html')},
redirect: ${JSON.stringify(pagePath)}
path: ${JSON.stringify(getUrlSafePath(pagePath + 'index.html'))},
redirect: ${JSON.stringify(getUrlSafePath(pagePath))}
}`
}

Expand Down
12 changes: 12 additions & 0 deletions lib/util/index.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
const spawn = require('cross-spawn')
const parseHeaders = require('./parseHeaders')
const shared = require('./shared')

Object.assign(exports, shared)

exports.parseHeaders = parseHeaders

Expand Down Expand Up @@ -88,3 +91,12 @@ exports.extractHeaders = (content, include = [], md) => {
exports.getGitLastUpdatedTimeStamp = filepath => {
return parseInt(spawn.sync('git', ['log', '-1', '--format=%ct', filepath]).stdout.toString('utf-8')) * 1000
}

let pageComponentID = 0
const pageComponentsCache = new Map()
exports.getPageComponentName = pagePath => {
if (!pageComponentsCache.has(pagePath)) {
pageComponentsCache.set(pagePath, `page-${pageComponentID++}`)
}
return pageComponentsCache.get(pagePath)
}
9 changes: 9 additions & 0 deletions lib/util/shared.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
exports.getUrlSafePath = rawPath => {
const [path, anchor] = rawPath.split(/#(?=[^#]*$)/)
return (
path
.split(/[/\\]+/)
.map(name => encodeURIComponent(name))
.join('/')
) + (anchor ? `#${anchor}` : '')
}
5 changes: 5 additions & 0 deletions lib/webpack/createBaseConfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ module.exports = function createBaseConfig ({
const Config = require('webpack-chain')
const { VueLoaderPlugin } = require('vue-loader')
const CSSExtractPlugin = require('mini-css-extract-plugin')
const VirtualModulesPlugin = require('webpack-virtual-modules')

const isProd = process.env.NODE_ENV === 'production'
const inlineLimit = 10000
Expand Down Expand Up @@ -255,5 +256,9 @@ module.exports = function createBaseConfig ({
SW_ENABLED: !!siteConfig.serviceWorker
}])

config
.plugin('virtual-modules')
.use(VirtualModulesPlugin, [require('../app/.temp/pageContent')])

return config
}
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,7 @@
"webpack-chain": "^4.6.0",
"webpack-merge": "^4.1.2",
"webpack-serve": "^0.3.1",
"webpack-virtual-modules": "^0.1.10",
"webpackbar": "^2.6.1",
"workbox-build": "^3.1.0"
},
Expand Down
8 changes: 7 additions & 1 deletion yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -2230,7 +2230,7 @@ de-indent@^1.0.2:
version "1.0.2"
resolved "https://registry.yarnpkg.com/de-indent/-/de-indent-1.0.2.tgz#b2038e846dc33baa5796128d0804b455b8c1e21d"

debug@*, debug@^3.1.0:
debug@*, debug@^3.0.0, debug@^3.1.0:
version "3.1.0"
resolved "https://registry.yarnpkg.com/debug/-/debug-3.1.0.tgz#5bb5a0672628b64149566ba16819e61518c67261"
dependencies:
Expand Down Expand Up @@ -7472,6 +7472,12 @@ webpack-sources@^1.0.1, webpack-sources@^1.1.0:
source-list-map "^2.0.0"
source-map "~0.6.1"

webpack-virtual-modules@^0.1.10:
version "0.1.10"
resolved "https://registry.yarnpkg.com/webpack-virtual-modules/-/webpack-virtual-modules-0.1.10.tgz#2039529cbf1007e19f6e897c8d35721cc2c41f68"
dependencies:
debug "^3.0.0"

webpack@^4.8.1:
version "4.8.1"
resolved "https://registry.yarnpkg.com/webpack/-/webpack-4.8.1.tgz#59e38f99f2751c931dd09a035aba7bec4b5f916e"
Expand Down