Nuxt/packages/utils/src/resolve.js

111 lines
2.7 KiB
JavaScript
Raw Normal View History

2018-12-22 21:05:13 +00:00
import path from 'path'
import consola from 'consola'
import escapeRegExp from 'lodash/escapeRegExp'
export const startsWithAlias = aliasArray => str => aliasArray.some(c => str.startsWith(c))
export const startsWithSrcAlias = startsWithAlias(['@', '~'])
export const startsWithRootAlias = startsWithAlias(['@@', '~~'])
export const isWindows = process.platform.startsWith('win')
2018-12-22 21:05:13 +00:00
export const wp = function wp (p = '') {
2018-12-22 21:05:13 +00:00
if (isWindows) {
return p.replace(/\\/g, '\\\\')
}
return p
}
export const wChunk = function wChunk (p = '') {
// workaround for SplitChunksPlugin that generate names starting from . for catchAll pages _.vue
// consider using https://webpack.js.org/configuration/output/#outputfilename for more robust control over filename generation
return p.replace('_', '[_]')
2018-12-22 21:05:13 +00:00
}
const reqSep = /\//g
const sysSep = escapeRegExp(path.sep)
const normalize = string => string.replace(reqSep, sysSep)
export const r = function r (...args) {
2018-12-22 21:05:13 +00:00
const lastArg = args[args.length - 1]
if (startsWithSrcAlias(lastArg)) {
return wp(lastArg)
}
return wp(path.resolve(...args.map(normalize)))
}
export const relativeTo = function relativeTo (...args) {
2018-12-22 21:05:13 +00:00
const dir = args.shift()
// Keep webpack inline loader intact
if (args[0].includes('!')) {
const loaders = args.shift().split('!')
return loaders.concat(relativeTo(dir, loaders.pop(), ...args)).join('!')
}
// Resolve path
const resolvedPath = r(...args)
2018-12-22 21:05:13 +00:00
// Check if path is an alias
if (startsWithSrcAlias(resolvedPath)) {
return resolvedPath
2018-12-22 21:05:13 +00:00
}
// Make correct relative path
let rp = path.relative(dir, resolvedPath)
2018-12-22 21:05:13 +00:00
if (rp[0] !== '.') {
rp = '.' + path.sep + rp
2018-12-22 21:05:13 +00:00
}
return wp(rp)
}
export function defineAlias (src, target, prop, opts = {}) {
2018-12-22 21:05:13 +00:00
const { bind = true, warn = false } = opts
if (Array.isArray(prop)) {
for (const p of prop) {
defineAlias(src, target, p, opts)
}
return
}
let targetVal = target[prop]
if (bind && typeof targetVal === 'function') {
targetVal = targetVal.bind(target)
}
let warned = false
Object.defineProperty(src, prop, {
get: () => {
if (warn && !warned) {
warned = true
consola.warn({
message: `'${prop}' is deprecated'`,
additional: new Error().stack.split('\n').splice(2).join('\n')
})
}
return targetVal
}
})
}
const isIndex = s => /(.*)\/index\.[^/]+$/.test(s)
export function isIndexFileAndFolder (pluginFiles) {
// Return early in case the matching file count exceeds 2 (index.js + folder)
if (pluginFiles.length !== 2) {
return false
}
return pluginFiles.some(isIndex)
}
2019-01-14 20:31:39 +00:00
2020-03-02 18:15:00 +00:00
export const getMainModule = () => {
return require.main || (module && module.main) || module
}