npm and error messages

This commit is contained in:
2018-10-27 03:51:47 -05:00
parent 692ab70565
commit 025a403027
29601 changed files with 2759363 additions and 14 deletions

21
node_modules/vue-loader/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2015-present Yuxi (Evan) You
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

21
node_modules/vue-loader/README.md generated vendored Normal file
View File

@@ -0,0 +1,21 @@
# vue-loader [![Build Status](https://circleci.com/gh/vuejs/vue-loader/tree/master.svg?style=shield)](https://circleci.com/gh/vuejs/vue-loader/tree/master) [![Windows Build status](https://ci.appveyor.com/api/projects/status/8cdonrkbg6m4k1tm/branch/master?svg=true)](https://ci.appveyor.com/project/yyx990803/vue-loader/branch/master) [![npm package](https://img.shields.io/npm/v/vue-loader.svg?maxAge=2592000)](https://www.npmjs.com/package/vue-loader)
> Vue.js component loader for [Webpack](https://webpack.js.org/).
<p align="center">
<img width="809px" src="https://raw.githubusercontent.com/vuejs/vue-syntax-highlight/master/samples/screenshot.png">
</p>
The best way to get started is with [vue-cli](https://github.com/vuejs/vue-cli):
``` js
npm install -g vue-cli
vue init webpack-simple hello
cd hello
npm install
npm run dev
```
This will setup a basic Webpack + `vue-loader` project for you, with `*.vue` files and hot-reloading working out of the box!
For advanced `vue-loader` configuration, checkout the [documentation](https://vue-loader.vuejs.org).

1
node_modules/vue-loader/index.js generated vendored Normal file
View File

@@ -0,0 +1 @@
module.exports = require('./lib/loader')

BIN
node_modules/vue-loader/lib/.DS_Store generated vendored Normal file

Binary file not shown.

103
node_modules/vue-loader/lib/component-normalizer.js generated vendored Normal file
View File

@@ -0,0 +1,103 @@
/* globals __VUE_SSR_CONTEXT__ */
// IMPORTANT: Do NOT use ES2015 features in this file.
// This module is a runtime utility for cleaner component module output and will
// be included in the final webpack user bundle.
module.exports = function normalizeComponent (
rawScriptExports,
compiledTemplate,
functionalTemplate,
injectStyles,
scopeId,
moduleIdentifier /* server only */
) {
var esModule
var scriptExports = rawScriptExports = rawScriptExports || {}
// ES6 modules interop
var type = typeof rawScriptExports.default
if (type === 'object' || type === 'function') {
esModule = rawScriptExports
scriptExports = rawScriptExports.default
}
// Vue.extend constructor export interop
var options = typeof scriptExports === 'function'
? scriptExports.options
: scriptExports
// render functions
if (compiledTemplate) {
options.render = compiledTemplate.render
options.staticRenderFns = compiledTemplate.staticRenderFns
options._compiled = true
}
// functional template
if (functionalTemplate) {
options.functional = true
}
// scopedId
if (scopeId) {
options._scopeId = scopeId
}
var hook
if (moduleIdentifier) { // server build
hook = function (context) {
// 2.3 injection
context =
context || // cached call
(this.$vnode && this.$vnode.ssrContext) || // stateful
(this.parent && this.parent.$vnode && this.parent.$vnode.ssrContext) // functional
// 2.2 with runInNewContext: true
if (!context && typeof __VUE_SSR_CONTEXT__ !== 'undefined') {
context = __VUE_SSR_CONTEXT__
}
// inject component styles
if (injectStyles) {
injectStyles.call(this, context)
}
// register component module identifier for async chunk inferrence
if (context && context._registeredComponents) {
context._registeredComponents.add(moduleIdentifier)
}
}
// used by ssr in case component is cached and beforeCreate
// never gets called
options._ssrRegister = hook
} else if (injectStyles) {
hook = injectStyles
}
if (hook) {
var functional = options.functional
var existing = functional
? options.render
: options.beforeCreate
if (!functional) {
// inject component registration as beforeCreate hook
options.beforeCreate = existing
? [].concat(existing, hook)
: [hook]
} else {
// for template-only hot-reload because in that case the render fn doesn't
// go through the normalizer
options._injectStyles = hook
// register for functioal component in vue file
options.render = function renderWithStyleInjection (h, context) {
hook.call(context)
return existing(h, context)
}
}
}
return {
esModule: esModule,
exports: scriptExports,
options: options
}
}

719
node_modules/vue-loader/lib/loader.js generated vendored Normal file
View File

@@ -0,0 +1,719 @@
const path = require('path')
const hash = require('hash-sum')
const parse = require('./parser')
const querystring = require('querystring')
const loaderUtils = require('loader-utils')
const normalize = require('./utils/normalize')
const tryRequire = require('./utils/try-require')
// internal lib loaders
const selectorPath = normalize.lib('selector')
const styleCompilerPath = normalize.lib('style-compiler/index')
const templateCompilerPath = normalize.lib('template-compiler/index')
const templatePreprocessorPath = normalize.lib('template-compiler/preprocessor')
const componentNormalizerPath = normalize.lib('component-normalizer')
// dep loaders
const styleLoaderPath = normalize.dep('vue-style-loader')
const hotReloadAPIPath = normalize.dep('vue-hot-reload-api')
// check whether default js loader exists
const hasBabel = !!tryRequire('babel-loader')
const hasBuble = !!tryRequire('buble-loader')
const rewriterInjectRE = /\b(css(?:-loader)?(?:\?[^!]+)?)(?:!|$)/
const defaultLang = {
template: 'html',
styles: 'css',
script: 'js'
}
const postcssExtensions = [
'postcss', 'pcss', 'sugarss', 'sss'
]
// When extracting parts from the source vue file, we want to apply the
// loaders chained before vue-loader, but exclude some loaders that simply
// produces side effects such as linting.
function getRawRequest (
{ resource, loaderIndex, loaders },
excludedPreLoaders = /eslint-loader/
) {
return loaderUtils.getRemainingRequest({
resource: resource,
loaderIndex: loaderIndex,
loaders: loaders.filter(loader => !excludedPreLoaders.test(loader.path))
})
}
module.exports = function (content) {
this.cacheable()
const isServer = this.target === 'node'
const isProduction = this.minimize || process.env.NODE_ENV === 'production'
const loaderContext = this
const query = loaderUtils.getOptions(this) || {}
const options = Object.assign(
{
esModule: true
},
this.options.vue,
this.vue,
query
)
// disable esModule in inject mode
// because import/export must be top-level
if (query.inject) {
options.esModule = false
}
// #824 avoid multiple webpack runs complaining about unknown option
Object.defineProperty(this.options, '__vueOptions__', {
value: options,
enumerable: false,
configurable: true
})
const rawRequest = getRawRequest(this, options.excludedPreLoaders)
const filePath = this.resourcePath
const fileName = path.basename(filePath)
const context =
(this._compiler && this._compiler.context) ||
this.options.context ||
process.cwd()
const sourceRoot = path.dirname(path.relative(context, filePath))
const shortFilePath = path.relative(context, filePath).replace(/^(\.\.[\\\/])+/, '').replace(/\\/g, '/')
const moduleId = 'data-v-' + hash(isProduction ? (shortFilePath + '\n' + content) : shortFilePath)
let cssLoaderOptions = ''
const cssSourceMap =
!isProduction &&
this.sourceMap &&
options.cssSourceMap !== false
if (cssSourceMap) {
cssLoaderOptions += '?sourceMap'
}
if (isProduction) {
cssLoaderOptions += (cssLoaderOptions ? '&' : '?') + 'minimize'
}
const bubleOptions =
hasBuble && options.buble ? '?' + JSON.stringify(options.buble) : ''
let output = ''
const parts = parse(
content,
fileName,
this.sourceMap,
sourceRoot,
cssSourceMap
)
const hasScoped = parts.styles.some(({ scoped }) => scoped)
const templateAttrs =
parts.template && parts.template.attrs && parts.template.attrs
const hasComment = templateAttrs && templateAttrs.comments
const functionalTemplate = templateAttrs && templateAttrs.functional
const bubleTemplateOptions = Object.assign({}, options.buble)
bubleTemplateOptions.transforms = Object.assign(
{},
bubleTemplateOptions.transforms
)
bubleTemplateOptions.transforms.stripWithFunctional = functionalTemplate
const templateCompilerOptions =
'?' +
JSON.stringify({
id: moduleId,
hasScoped,
hasComment,
transformToRequire: options.transformToRequire,
preserveWhitespace: options.preserveWhitespace,
buble: bubleTemplateOptions,
// only pass compilerModules if it's a path string
compilerModules:
typeof options.compilerModules === 'string'
? options.compilerModules
: undefined
})
const defaultLoaders = {
html: templateCompilerPath + templateCompilerOptions,
css: options.extractCSS
? getCSSExtractLoader()
: styleLoaderPath + '!' + 'css-loader' + cssLoaderOptions,
js: hasBuble
? 'buble-loader' + bubleOptions
: hasBabel ? 'babel-loader' : ''
}
// check if there are custom loaders specified via
// webpack config, otherwise use defaults
const loaders = Object.assign({}, defaultLoaders, options.loaders)
const preLoaders = options.preLoaders || {}
const postLoaders = options.postLoaders || {}
const needsHotReload =
!isServer && !isProduction && (parts.script || parts.template) && options.hotReload !== false
if (needsHotReload) {
output += 'var disposed = false\n'
}
// add requires for styles
let cssModules
if (parts.styles.length) {
let styleInjectionCode = 'function injectStyle (ssrContext) {\n'
if (needsHotReload) {
styleInjectionCode += ` if (disposed) return\n`
}
if (isServer) {
styleInjectionCode += `var i\n`
}
parts.styles.forEach((style, i) => {
// require style
let requireString = style.src
? getRequireForImport('styles', style, style.scoped)
: getRequire('styles', style, i, style.scoped)
const hasStyleLoader = requireString.indexOf('style-loader') > -1
const hasVueStyleLoader = requireString.indexOf('vue-style-loader') > -1
// vue-style-loader exposes inject functions during SSR so they are
// always called
const invokeStyle =
isServer && hasVueStyleLoader
? code => `;(i=${code},i.__inject__&&i.__inject__(ssrContext),i)\n`
: code => ` ${code}\n`
const moduleName = style.module === true ? '$style' : style.module
// setCssModule
if (moduleName) {
if (!cssModules) {
cssModules = {}
if (needsHotReload) {
output += `var cssModules = {}\n`
}
}
if (moduleName in cssModules) {
loaderContext.emitError(
'CSS module name "' + moduleName + '" is not unique!'
)
styleInjectionCode += invokeStyle(requireString)
} else {
cssModules[moduleName] = true
// `(vue-)style-loader` exposes the name-to-hash map directly
// `css-loader` exposes it in `.locals`
// add `.locals` if the user configured to not use style-loader.
if (!hasStyleLoader) {
requireString += '.locals'
}
if (!needsHotReload) {
styleInjectionCode += invokeStyle(
'this["' + moduleName + '"] = ' + requireString
)
} else {
// handle hot reload for CSS modules.
// we store the exported locals in an object and proxy to it by
// defining getters inside component instances' lifecycle hook.
styleInjectionCode +=
invokeStyle(`cssModules["${moduleName}"] = ${requireString}`) +
`Object.defineProperty(this, "${moduleName}", { get: function () { return cssModules["${moduleName}"] }})\n`
const requirePath = style.src
? getRequireForImportString('styles', style, style.scoped)
: getRequireString('styles', style, i, style.scoped)
output +=
`module.hot && module.hot.accept([${requirePath}], function () {\n` +
// 1. check if style has been injected
` var oldLocals = cssModules["${moduleName}"]\n` +
` if (!oldLocals) return\n` +
// 2. re-import (side effect: updates the <style>)
` var newLocals = ${requireString}\n` +
// 3. compare new and old locals to see if selectors changed
` if (JSON.stringify(newLocals) === JSON.stringify(oldLocals)) return\n` +
// 4. locals changed. Update and force re-render.
` cssModules["${moduleName}"] = newLocals\n` +
` require("${hotReloadAPIPath}").rerender("${moduleId}")\n` +
`})\n`
}
}
} else {
styleInjectionCode += invokeStyle(requireString)
}
})
styleInjectionCode += '}\n'
output += styleInjectionCode
}
// we require the component normalizer function, and call it like so:
// normalizeComponent(
// scriptExports,
// compiledTemplate,
// functionalTemplate,
// injectStyles,
// scopeId,
// moduleIdentifier (server only)
// )
output +=
'var normalizeComponent = require(' +
loaderUtils.stringifyRequest(loaderContext, '!' + componentNormalizerPath) +
')\n'
// <script>
output += '/* script */\n'
const script = parts.script
if (script) {
if (options.esModule) {
output += script.src
? (
getNamedExportForImport('script', script) + '\n' +
getImportForImport('script', script)
)
: (
getNamedExport('script', script) + '\n' +
getImport('script', script)
) + '\n'
} else {
output +=
'var __vue_script__ = ' +
(script.src
? getRequireForImport('script', script)
: getRequire('script', script)) +
'\n'
}
// inject loader interop
if (query.inject) {
output += '__vue_script__ = __vue_script__(injections)\n'
}
} else {
output += 'var __vue_script__ = null\n'
}
// <template>
output += '/* template */\n'
const template = parts.template
if (template) {
if (options.esModule) {
output +=
(template.src
? getImportForImport('template', template)
: getImport('template', template)) + '\n'
} else {
output +=
'var __vue_template__ = ' +
(template.src
? getRequireForImport('template', template)
: getRequire('template', template)) +
'\n'
}
} else {
output += 'var __vue_template__ = null\n'
}
// template functional
output += '/* template functional */\n'
output +=
'var __vue_template_functional__ = ' +
(functionalTemplate ? 'true' : 'false') +
'\n'
// style
output += '/* styles */\n'
output +=
'var __vue_styles__ = ' +
(parts.styles.length ? 'injectStyle' : 'null') +
'\n'
// scopeId
output += '/* scopeId */\n'
output +=
'var __vue_scopeId__ = ' +
(hasScoped ? JSON.stringify(moduleId) : 'null') +
'\n'
// moduleIdentifier (server only)
output += '/* moduleIdentifier (server only) */\n'
output +=
'var __vue_module_identifier__ = ' +
(isServer ? JSON.stringify(hash(this.request)) : 'null') +
'\n'
// close normalizeComponent call
output +=
'var Component = normalizeComponent(\n' +
' __vue_script__,\n' +
' __vue_template__,\n' +
' __vue_template_functional__,\n' +
' __vue_styles__,\n' +
' __vue_scopeId__,\n' +
' __vue_module_identifier__\n' +
')\n'
// development-only code
if (!isProduction) {
// add filename in dev
output +=
'Component.options.__file = ' + JSON.stringify(shortFilePath) + '\n'
}
// add requires for customBlocks
if (parts.customBlocks && parts.customBlocks.length) {
let addedPrefix = false
parts.customBlocks.forEach((customBlock, i) => {
if (loaders[customBlock.type]) {
// require customBlock
customBlock.src = customBlock.attrs.src
const requireString = customBlock.src
? getRequireForImport(customBlock.type, customBlock)
: getRequire(customBlock.type, customBlock, i)
if (!addedPrefix) {
output += '\n/* customBlocks */\n'
addedPrefix = true
}
output +=
'var customBlock = ' + requireString + '\n' +
'if (customBlock && customBlock.__esModule) {\n' +
' customBlock = customBlock.default\n' +
'}\n' +
'if (typeof customBlock === "function") {\n' +
' customBlock(Component)\n' +
'}\n'
}
})
output += '\n'
}
if (!query.inject) {
// hot reload
if (needsHotReload) {
output +=
'\n/* hot reload */\n' +
'if (module.hot) {(function () {\n' +
' var hotAPI = require("' + hotReloadAPIPath + '")\n' +
' hotAPI.install(require("vue"), false)\n' +
' if (!hotAPI.compatible) return\n' +
' module.hot.accept()\n' +
' if (!module.hot.data) {\n' +
// initial insert
' hotAPI.createRecord("' + moduleId + '", Component.options)\n' +
' } else {\n'
// update
if (cssModules) {
output +=
' if (module.hot.data.cssModules && Object.keys(module.hot.data.cssModules) !== Object.keys(cssModules)) {\n' +
' delete Component.options._Ctor\n' +
' }\n'
}
output +=
` hotAPI.${
functionalTemplate ? 'rerender' : 'reload'
}("${moduleId}", Component.options)\n }\n`
// dispose
output +=
' module.hot.dispose(function (data) {\n' +
(cssModules ? ' data.cssModules = cssModules\n' : '') +
' disposed = true\n' +
' })\n'
output += '})()}\n'
}
// final export
if (options.esModule) {
output += '\nexport default Component.exports\n'
} else {
output += '\nmodule.exports = Component.exports\n'
}
} else {
// inject-loader support
output =
'\n/* dependency injection */\n' +
'module.exports = function (injections) {\n' +
output +
'\n' +
'\nreturn Component.exports\n}'
}
// done
return output
// --- helpers ---
function getRequire (type, part, index, scoped) {
return 'require(' + getRequireString(type, part, index, scoped) + ')'
}
function getImport (type, part, index, scoped) {
return (
'import __vue_' + type + '__ from ' +
getRequireString(type, part, index, scoped)
)
}
function getNamedExport (type, part, index, scoped) {
return (
'export * from ' +
getRequireString(type, part, index, scoped)
)
}
function getRequireString (type, part, index, scoped) {
return loaderUtils.stringifyRequest(
loaderContext,
// disable all configuration loaders
'!!' +
// get loader string for pre-processors
getLoaderString(type, part, index, scoped) +
// select the corresponding part from the vue file
getSelectorString(type, index || 0) +
// the url to the actual vue file, including remaining requests
rawRequest
)
}
function getRequireForImport (type, impt, scoped) {
return 'require(' + getRequireForImportString(type, impt, scoped) + ')'
}
function getImportForImport (type, impt, scoped) {
return (
'import __vue_' + type + '__ from ' +
getRequireForImportString(type, impt, scoped)
)
}
function getNamedExportForImport (type, impt, scoped) {
return (
'export * from ' +
getRequireForImportString(type, impt, scoped)
)
}
function getRequireForImportString (type, impt, scoped) {
return loaderUtils.stringifyRequest(
loaderContext,
'!!' + getLoaderString(type, impt, -1, scoped) + impt.src
)
}
function addCssModulesToLoader (loader, part, index) {
if (!part.module) return loader
const option = options.cssModules || {}
const DEFAULT_OPTIONS = {
modules: true
}
const OPTIONS = {
localIdentName: '[hash:base64]',
importLoaders: true
}
return loader.replace(/((?:^|!)css(?:-loader)?)(\?[^!]*)?/, (m, $1, $2) => {
// $1: !css-loader
// $2: ?a=b
const query = loaderUtils.parseQuery($2 || '?')
Object.assign(query, OPTIONS, option, DEFAULT_OPTIONS)
if (index !== -1) {
// Note:
// Class name is generated according to its filename.
// Different <style> tags in the same .vue file may generate same names.
// Append `_[index]` to class name to avoid this.
query.localIdentName += '_' + index
}
return $1 + '?' + JSON.stringify(query)
})
}
function buildCustomBlockLoaderString (attrs) {
const noSrcAttrs = Object.assign({}, attrs)
delete noSrcAttrs.src
const qs = querystring.stringify(noSrcAttrs)
return qs ? '?' + qs : qs
}
// stringify an Array of loader objects
function stringifyLoaders (loaders) {
return loaders
.map(
obj =>
obj && typeof obj === 'object' && typeof obj.loader === 'string'
? obj.loader +
(obj.options ? '?' + JSON.stringify(obj.options) : '')
: obj
)
.join('!')
}
function getLoaderString (type, part, index, scoped) {
let loader = getRawLoaderString(type, part, index, scoped)
const lang = getLangString(type, part)
if (preLoaders[lang]) {
loader = loader + ensureBang(preLoaders[lang])
}
if (postLoaders[lang]) {
loader = ensureBang(postLoaders[lang]) + loader
}
return loader
}
function getLangString (type, { lang }) {
if (type === 'script' || type === 'template' || type === 'styles') {
return lang || defaultLang[type]
} else {
return type
}
}
function getRawLoaderString (type, part, index, scoped) {
let lang = part.lang || defaultLang[type]
let styleCompiler = ''
if (type === 'styles') {
// style compiler that needs to be applied for all styles
styleCompiler =
styleCompilerPath +
'?' +
JSON.stringify({
// a marker for vue-style-loader to know that this is an import from a vue file
vue: true,
id: moduleId,
scoped: !!scoped,
hasInlineConfig: !!query.postcss
}) +
'!'
// normalize scss/sass/postcss if no specific loaders have been provided
if (!loaders[lang]) {
if (postcssExtensions.indexOf(lang) !== -1) {
lang = 'css'
} else if (lang === 'sass') {
lang = 'sass?indentedSyntax'
} else if (lang === 'scss') {
lang = 'sass'
}
}
}
let loader =
options.extractCSS && type === 'styles'
? loaders[lang] || getCSSExtractLoader(lang)
: loaders[lang]
const injectString =
type === 'script' && query.inject ? 'inject-loader!' : ''
if (loader != null) {
if (Array.isArray(loader)) {
loader = stringifyLoaders(loader)
} else if (typeof loader === 'object') {
loader = stringifyLoaders([loader])
}
if (type === 'styles') {
// add css modules
loader = addCssModulesToLoader(loader, part, index)
// inject rewriter before css loader for extractTextPlugin use cases
if (rewriterInjectRE.test(loader)) {
loader = loader.replace(
rewriterInjectRE,
(m, $1) => ensureBang($1) + styleCompiler
)
} else {
loader = ensureBang(loader) + styleCompiler
}
}
// if user defines custom loaders for html, add template compiler to it
if (type === 'template' && loader.indexOf(defaultLoaders.html) < 0) {
loader = defaultLoaders.html + '!' + loader
}
return injectString + ensureBang(loader)
} else {
// unknown lang, infer the loader to be used
switch (type) {
case 'template':
return (
defaultLoaders.html +
'!' +
templatePreprocessorPath +
'?engine=' +
lang +
'!'
)
case 'styles':
loader = addCssModulesToLoader(defaultLoaders.css, part, index)
return loader + '!' + styleCompiler + ensureBang(ensureLoader(lang))
case 'script':
return injectString + ensureBang(ensureLoader(lang))
default:
loader = loaders[type]
if (Array.isArray(loader)) {
loader = stringifyLoaders(loader)
}
return ensureBang(loader + buildCustomBlockLoaderString(part.attrs))
}
}
}
// sass => sass-loader
// sass-loader => sass-loader
// sass?indentedSyntax!css => sass-loader?indentedSyntax!css-loader
function ensureLoader (lang) {
return lang
.split('!')
.map(loader =>
loader.replace(
/^([\w-]+)(\?.*)?/,
(_, name, query) =>
(/-loader$/.test(name) ? name : name + '-loader') + (query || '')
)
)
.join('!')
}
function getSelectorString (type, index) {
return (
selectorPath +
'?type=' +
(type === 'script' || type === 'template' || type === 'styles'
? type
: 'customBlocks') +
'&index=' + index +
'!'
)
}
function ensureBang (loader) {
if (loader.charAt(loader.length - 1) !== '!') {
return loader + '!'
} else {
return loader
}
}
function getCSSExtractLoader (lang) {
let extractor
const op = options.extractCSS
// extractCSS option is an instance of ExtractTextPlugin
if (typeof op.extract === 'function') {
extractor = op
} else {
extractor = tryRequire('extract-text-webpack-plugin')
if (!extractor) {
throw new Error(
'[vue-loader] extractCSS: true requires extract-text-webpack-plugin ' +
'as a peer dependency.'
)
}
}
const langLoader = lang ? ensureBang(ensureLoader(lang)) : ''
return extractor.extract({
use: 'css-loader' + cssLoaderOptions + '!' + langLoader,
fallback: 'vue-style-loader'
})
}
}

BIN
node_modules/vue-loader/lib/loaders/.DS_Store generated vendored Normal file

Binary file not shown.

59
node_modules/vue-loader/lib/parser.js generated vendored Normal file
View File

@@ -0,0 +1,59 @@
const compiler = require('vue-template-compiler')
const cache = require('lru-cache')(100)
const hash = require('hash-sum')
const SourceMapGenerator = require('source-map').SourceMapGenerator
const splitRE = /\r?\n/g
const emptyRE = /^(?:\/\/)?\s*$/
module.exports = (content, filename, needMap, sourceRoot, needCSSMap) => {
const cacheKey = hash((filename + content).replace(/\\/g, '/'))
let output = cache.get(cacheKey)
if (output) return output
output = compiler.parseComponent(content, { pad: 'line' })
if (needMap) {
if (output.script && !output.script.src) {
output.script.map = generateSourceMap(
filename,
content,
output.script.content,
sourceRoot
)
}
if (needCSSMap && output.styles) {
output.styles.forEach(style => {
if (!style.src) {
style.map = generateSourceMap(
filename,
content,
style.content,
sourceRoot
)
}
})
}
}
cache.set(cacheKey, output)
return output
}
function generateSourceMap (filename, source, generated, sourceRoot) {
const map = new SourceMapGenerator({ sourceRoot })
map.setSourceContent(filename, source)
generated.split(splitRE).forEach((line, index) => {
if (!emptyRE.test(line)) {
map.addMapping({
source: filename,
original: {
line: index + 1,
column: 0
},
generated: {
line: index + 1,
column: 0
}
})
}
})
return map.toJSON()
}

22
node_modules/vue-loader/lib/selector.js generated vendored Normal file
View File

@@ -0,0 +1,22 @@
// this is a utility loader that takes a *.vue file, parses it and returns
// the requested language block, e.g. the content inside <template>, for
// further processing.
const path = require('path')
const parse = require('./parser')
const loaderUtils = require('loader-utils')
module.exports = function (content) {
this.cacheable()
const query = loaderUtils.getOptions(this) || {}
const context = (this._compiler && this._compiler.context) || this.options.context || process.cwd()
let filename = path.basename(this.resourcePath)
filename = filename.substring(0, filename.lastIndexOf(path.extname(filename))) + '.vue'
const sourceRoot = path.dirname(path.relative(context, this.resourcePath))
const parts = parse(content, filename, this.sourceMap, sourceRoot)
let part = parts[query.type]
if (Array.isArray(part)) {
part = part[query.index]
}
this.callback(null, part.content, part.map)
}

79
node_modules/vue-loader/lib/style-compiler/index.js generated vendored Normal file
View File

@@ -0,0 +1,79 @@
const postcss = require('postcss')
const loaderUtils = require('loader-utils')
const loadPostcssConfig = require('./load-postcss-config')
const trim = require('./plugins/trim')
const scopeId = require('./plugins/scope-id')
module.exports = function (css, map) {
this.cacheable()
const cb = this.async()
const query = loaderUtils.getOptions(this) || {}
let vueOptions = this.options.__vueOptions__
if (!vueOptions) {
if (query.hasInlineConfig) {
this.emitError(
`\n [vue-loader] It seems you are using HappyPack with inline postcss ` +
`options for vue-loader. This is not supported because loaders running ` +
`in different threads cannot share non-serializable options. ` +
`It is recommended to use a postcss config file instead.\n` +
`\n See http://vue-loader.vuejs.org/en/features/postcss.html#using-a-config-file for more details.\n`
)
}
vueOptions = Object.assign({}, this.options.vue, this.vue)
}
loadPostcssConfig(this, vueOptions.postcss)
.then(config => {
const plugins = config.plugins.concat(trim)
const options = Object.assign(
{
to: this.resourcePath,
from: this.resourcePath,
map: false
},
config.options
)
// add plugin for vue-loader scoped css rewrite
if (query.scoped) {
plugins.push(scopeId({ id: query.id }))
}
// source map
if (
this.sourceMap &&
!this.minimize &&
vueOptions.cssSourceMap !== false &&
process.env.NODE_ENV !== 'production' &&
!options.map
) {
options.map = {
inline: false,
annotation: false,
prev: map
}
}
return postcss(plugins)
.process(css, options)
.then(result => {
if (result.messages) {
result.messages.forEach(({ type, file }) => {
if (type === 'dependency') {
this.addDependency(file)
}
})
}
const map = result.map && result.map.toJSON()
cb(null, result.css, map)
return null // silence bluebird warning
})
})
.catch(e => {
console.error(e)
cb(e)
})
}

View File

@@ -0,0 +1,66 @@
const load = require('postcss-load-config')
let loaded
function isObject (val) {
return val && typeof val === 'object'
}
module.exports = function loadPostcssConfig (loaderContext, inlineConfig = {}) {
if (inlineConfig.useConfigFile === false) {
return Promise.resolve({
plugins: inlineConfig.plugins || [],
options: inlineConfig.options || {}
})
}
if (process.env.VUE_LOADER_TEST || !loaded) {
const config = inlineConfig.config || {}
const ctx = { webpack: loaderContext }
if (config.ctx) {
ctx.options = config.ctx
}
loaded = load(ctx, config.path, { argv: false }).catch(err => {
// postcss-load-config throws error when no config file is found,
// but for us it's optional. only emit other errors
if (err.message.indexOf('No PostCSS Config found') >= 0) {
return
}
const friendlyErr = new Error(`Error loading PostCSS config: ${err.message}`)
Error.captureStackTrace(friendlyErr, err)
loaderContext.emitError(friendlyErr)
})
}
return loaded.then(config => {
let plugins = []
let options = {}
// inline postcss options for vue-loader
if (typeof inlineConfig === 'function') {
inlineConfig = inlineConfig.call(this, this)
}
if (Array.isArray(inlineConfig)) {
plugins = inlineConfig
} else if (isObject(inlineConfig)) {
plugins =
typeof inlineConfig.plugins === 'function'
? inlineConfig.plugins.call(this, this)
: inlineConfig.plugins || []
options = inlineConfig.options || {}
}
// merge postcss config file
if (config && config.plugins) {
plugins = plugins.concat(config.plugins)
}
if (config && config.options) {
options = Object.assign({}, config.options, options)
}
return {
plugins,
options
}
})
}

View File

@@ -0,0 +1,79 @@
const postcss = require('postcss')
const selectorParser = require('postcss-selector-parser')
module.exports = postcss.plugin('add-id', ({ id }) => root => {
const keyframes = Object.create(null)
root.each(function rewriteSelector (node) {
if (!node.selector) {
// handle media queries
if (node.type === 'atrule') {
if (node.name === 'media' || node.name === 'supports') {
node.each(rewriteSelector)
} else if (/-?keyframes$/.test(node.name)) {
// register keyframes
keyframes[node.params] = node.params = node.params + '-' + id
}
}
return
}
node.selector = selectorParser(selectors => {
selectors.each(selector => {
let node = null
selector.each(n => {
// ">>>" combinator
if (n.type === 'combinator' && n.value === '>>>') {
n.value = ' '
n.spaces.before = n.spaces.after = ''
return false
}
// /deep/ alias for >>>, since >>> doesn't work in SASS
if (n.type === 'tag' && n.value === '/deep/') {
const prev = n.prev()
if (prev && prev.type === 'combinator' && prev.value === ' ') {
prev.remove()
}
n.remove()
return false
}
if (n.type !== 'pseudo' && n.type !== 'combinator') {
node = n
}
})
selector.insertAfter(node, selectorParser.attribute({
attribute: id
}))
})
}).process(node.selector).result
})
// If keyframes are found in this <style>, find and rewrite animation names
// in declarations.
// Caveat: this only works for keyframes and animation rules in the same
// <style> element.
if (Object.keys(keyframes).length) {
root.walkDecls(decl => {
// individual animation-name declaration
if (/-?animation-name$/.test(decl.prop)) {
decl.value = decl.value.split(',')
.map(v => keyframes[v.trim()] || v.trim())
.join(',')
}
// shorthand
if (/-?animation$/.test(decl.prop)) {
decl.value = decl.value.split(',')
.map(v => {
const vals = v.trim().split(/\s+/)
const i = vals.findIndex(val => keyframes[val])
if (i !== -1) {
vals.splice(i, 1, keyframes[vals[i]])
return vals.join(' ')
} else {
return v
}
})
.join(',')
}
})
}
})

View File

@@ -0,0 +1,9 @@
const postcss = require('postcss')
module.exports = postcss.plugin('trim', opts => css => {
css.walk(({ type, raws }) => {
if (type === 'rule' || type === 'atrule') {
raws.before = raws.after = '\n'
}
})
})

119
node_modules/vue-loader/lib/template-compiler/index.js generated vendored Normal file
View File

@@ -0,0 +1,119 @@
const prettier = require('prettier')
const loaderUtils = require('loader-utils')
const normalize = require('../utils/normalize')
const compiler = require('vue-template-compiler')
const transpile = require('vue-template-es2015-compiler')
const hotReloadAPIPath = normalize.dep('vue-hot-reload-api')
const transformRequire = require('./modules/transform-require')
const transformSrcset = require('./modules/transform-srcset')
module.exports = function (html) {
this.cacheable()
const isServer = this.target === 'node'
const isProduction = this.minimize || process.env.NODE_ENV === 'production'
const vueOptions = this.options.__vueOptions__ || {}
const options = loaderUtils.getOptions(this) || {}
const needsHotReload = !isServer && !isProduction && vueOptions.hotReload !== false
const defaultModules = [transformRequire(options.transformToRequire), transformSrcset()]
let userModules = vueOptions.compilerModules || options.compilerModules
// for HappyPack cross-process use cases
if (typeof userModules === 'string') {
userModules = require(userModules)
}
const compilerOptions = {
preserveWhitespace: options.preserveWhitespace,
modules: defaultModules.concat(userModules || []),
directives:
vueOptions.compilerDirectives || options.compilerDirectives || {},
scopeId: options.hasScoped ? options.id : null,
comments: options.hasComment
}
const compile =
isServer && compiler.ssrCompile && vueOptions.optimizeSSR !== false
? compiler.ssrCompile
: compiler.compile
const compiled = compile(html, compilerOptions)
// tips
if (compiled.tips && compiled.tips.length) {
compiled.tips.forEach(tip => {
this.emitWarning(tip)
})
}
let code
if (compiled.errors && compiled.errors.length) {
this.emitError(
`\n Error compiling template:\n${pad(html)}\n` +
compiled.errors.map(e => ` - ${e}`).join('\n') +
'\n'
)
code = vueOptions.esModule
? `var esExports = {render:function(){},staticRenderFns: []}\nexport default esExports`
: 'module.exports={render:function(){},staticRenderFns:[]}'
} else {
const bubleOptions = options.buble
const stripWith = bubleOptions.transforms.stripWith !== false
const stripWithFunctional = bubleOptions.transforms.stripWithFunctional
const staticRenderFns = compiled.staticRenderFns.map(fn =>
toFunction(fn, stripWithFunctional)
)
code =
transpile(
'var render = ' +
toFunction(compiled.render, stripWithFunctional) +
'\n' +
'var staticRenderFns = [' +
staticRenderFns.join(',') +
']',
bubleOptions
) + '\n'
// prettify render fn
if (!isProduction) {
code = prettier.format(code, { semi: false, parser: 'babylon' })
}
// mark with stripped (this enables Vue to use correct runtime proxy detection)
if (!isProduction && stripWith) {
code += `render._withStripped = true\n`
}
const exports = `{ render: render, staticRenderFns: staticRenderFns }`
code += vueOptions.esModule
? `var esExports = ${exports}\nexport default esExports`
: `module.exports = ${exports}`
}
// hot-reload
if (needsHotReload) {
const exportsName = vueOptions.esModule ? 'esExports' : 'module.exports'
code +=
'\nif (module.hot) {\n' +
' module.hot.accept()\n' +
' if (module.hot.data) {\n' +
' require("' + hotReloadAPIPath + '")' +
' .rerender("' + options.id + '", ' + exportsName + ')\n' +
' }\n' +
'}'
}
return code
}
function toFunction (code, stripWithFunctional) {
return (
'function (' + (stripWithFunctional ? '_h,_vm' : '') + ') {' + code + '}'
)
}
function pad (html) {
return html
.split(/\r?\n/)
.map(line => ` ${line}`)
.join('\n')
}

View File

@@ -0,0 +1,46 @@
// vue compiler module for transforming `<tag>:<attribute>` to `require`
const urlToRequire = require('../url-to-require')
const defaultOptions = {
video: ['src', 'poster'],
source: 'src',
img: 'src',
image: 'xlink:href'
}
module.exports = userOptions => {
const options = userOptions
? Object.assign({}, defaultOptions, userOptions)
: defaultOptions
return {
postTransformNode: node => {
transform(node, options)
}
}
}
function transform (node, options) {
for (const tag in options) {
if ((tag === '*' || node.tag === tag) && node.attrs) {
const attributes = options[tag]
if (typeof attributes === 'string') {
node.attrs.some(attr => rewrite(attr, attributes))
} else if (Array.isArray(attributes)) {
attributes.forEach(item => node.attrs.some(attr => rewrite(attr, item)))
}
}
}
}
function rewrite (attr, name) {
if (attr.name === name) {
const value = attr.value
// only transform static URLs
if (value.charAt(0) === '"' && value.charAt(value.length - 1) === '"') {
attr.value = urlToRequire(value.slice(1, -1))
return true
}
}
}

View File

@@ -0,0 +1,47 @@
// vue compiler module for transforming `img:srcset` to a number of `require`s
const urlToRequire = require('../url-to-require')
module.exports = () => ({
postTransformNode: node => {
transform(node)
}
})
function transform (node) {
const tags = ['img', 'source']
if (tags.indexOf(node.tag) !== -1 && node.attrs) {
node.attrs.forEach(attr => {
if (attr.name === 'srcset') {
// same logic as in transform-require.js
const value = attr.value
const isStatic = value.charAt(0) === '"' && value.charAt(value.length - 1) === '"'
if (!isStatic) {
return
}
// http://w3c.github.io/html/semantics-embedded-content.html#ref-for-image-candidate-string-5
const escapedSpaceCharacters = /( |\\t|\\n|\\f|\\r)+/g
const imageCandidates = value.substr(1, value.length - 2).split(',').map(s => {
// The attribute value arrives here with all whitespace, except normal spaces, represented by escape sequences
const [url, descriptor] = s.replace(escapedSpaceCharacters, ' ').trim().split(' ', 2)
return { require: urlToRequire(url), descriptor: descriptor }
})
// "require(url1)"
// "require(url1) 1x"
// "require(url1), require(url2)"
// "require(url1), require(url2) 2x"
// "require(url1) 1x, require(url2)"
// "require(url1) 1x, require(url2) 2x"
const code = imageCandidates.map(
({ require, descriptor }) => `${require} + "${descriptor ? ' ' + descriptor : ''}, " + `
).join('').slice(0, -6).concat('"').replace(/ \+ ""$/, '')
attr.value = code
}
})
}
}

View File

@@ -0,0 +1,36 @@
// loader for pre-processing templates with e.g. pug
const cons = require('consolidate')
const loaderUtils = require('loader-utils')
module.exports = function (content) {
this.cacheable && this.cacheable()
const callback = this.async()
const opt = loaderUtils.getOptions(this) || {}
if (!cons[opt.engine]) {
return callback(
new Error(
"Template engine '" +
opt.engine +
"' " +
"isn't available in Consolidate.js"
)
)
}
// allow passing options to the template preprocessor via `template` option
if (this.options.__vueOptions__) {
Object.assign(opt, this.options.__vueOptions__.template)
}
// for relative includes
opt.filename = this.resourcePath
cons[opt.engine].render(content, opt, (err, html) => {
if (err) {
return callback(err)
}
callback(null, html)
})
}

View File

@@ -0,0 +1,13 @@
module.exports = function urlToRequire (url) {
// same logic as in transform-require.js
const firstChar = url.charAt(0)
if (firstChar === '.' || firstChar === '~' || firstChar === '@') {
if (firstChar === '~') {
const secondChar = url.charAt(1)
url = url.slice(secondChar === '/' ? 2 : 1)
}
return `require("${url}")`
} else {
return `"${url}"`
}
}

19
node_modules/vue-loader/lib/utils/normalize.js generated vendored Normal file
View File

@@ -0,0 +1,19 @@
const IS_TEST = !!process.env.VUE_LOADER_TEST
const fs = require('fs')
const path = require('path')
exports.lib = file => path.resolve(__dirname, '../', file)
exports.dep = dep => {
if (IS_TEST) {
return dep
} else if (
fs.existsSync(path.resolve(__dirname, '../../node_modules', dep))
) {
// npm 2 or npm linked
return 'vue-loader/node_modules/' + dep
} else {
// npm 3
return dep
}
}

18
node_modules/vue-loader/lib/utils/try-require.js generated vendored Normal file
View File

@@ -0,0 +1,18 @@
const cwd = process.cwd()
const resolve = require('resolve')
// attempts to first require a dep using projects cwd (when vue-loader is linked)
// then try a normal require.
module.exports = function tryRequire (dep) {
let fromCwd
try {
fromCwd = resolve.sync(dep, { basedir: cwd })
} catch (e) {}
if (fromCwd) {
return require(fromCwd)
} else {
try {
return require(dep)
} catch (e) {}
}
}

View File

@@ -0,0 +1,56 @@
# Changelog
## 2.2.2
- Fixed: `options.configPath` and `--config` flag are respected.
## 2.2.0-1
- 2.2.0 included a number of improvements but somehow broke stylelint. The changes were reverted in 2.2.1, to be restored later.
## 2.1.3
- Licensing improvement: switched from `json-parse-helpfulerror` to `parse-json`.
## 2.1.2
- Fixed: bug where an `ENOENT` error would be thrown is `searchPath` referenced a non-existent file.
- Fixed: JSON parsing errors in Node v7.
## 2.1.1
- Fixed: swapped `graceful-fs` for regular `fs`, fixing a garbage collection problem.
## 2.1.0
- Added: Node 0.12 support.
## 2.0.2
- Fixed: Node version specified in `package.json`.
## 2.0.1
- Fixed: no more infinite loop in Windows.
## 2.0.0
- Changed: module now creates cosmiconfig instances with `load` methods (see README).
- Added: caching (enabled by the change above).
- Removed: support for Node versions <4.
## 1.1.0
- Add `rcExtensions` option.
## 1.0.2
- Fix handling of `require()`'s within JS module configs.
## 1.0.1
- Switch Promise implementation to pinkie-promise.
## 1.0.0
- Initial release.

View File

@@ -0,0 +1,22 @@
The MIT License (MIT)
Copyright (c) 2015 David Clark
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,226 @@
# cosmiconfig
[![Build Status](https://img.shields.io/travis/davidtheclark/cosmiconfig/master.svg?label=unix%20build)](https://travis-ci.org/davidtheclark/cosmiconfig) [![Build status](https://img.shields.io/appveyor/ci/davidtheclark/cosmiconfig/master.svg?label=windows%20build)](https://ci.appveyor.com/project/davidtheclark/cosmiconfig/branch/master)
Find and load a configuration object from
- a `package.json` property (anywhere down the file tree)
- a JSON or YAML "rc file" (anywhere down the file tree)
- a `.config.js` CommonJS module (anywhere down the file tree)
- a CLI `--config` argument
For example, if your module's name is "soursocks," cosmiconfig will search out configuration in the following places:
- a `soursocks` property in `package.json` (anywhere down the file tree)
- a `.soursocksrc` file in JSON or YAML format (anywhere down the file tree)
- a `soursocks.config.js` file exporting a JS object (anywhere down the file tree)
- a CLI `--config` argument
cosmiconfig continues to search in these places all the way down the file tree until it finds acceptable configuration (or hits the home directory). And it does all this asynchronously, so it shouldn't get in your way.
Additionally, all of these search locations are configurable: you can customize filenames or turn off any location.
You can also look for rc files with extensions, e.g. `.soursocksrc.json` or `.soursocksrc.yaml`.
You may like extensions on your rc files because you'll get syntax highlighting and linting in text editors.
## Installation
```
npm install cosmiconfig
```
Tested in Node 0.12+.
## Usage
```js
var cosmiconfig = require('cosmiconfig');
var explorer = cosmiconfig(yourModuleName[, options]);
explorer.load(yourSearchPath)
.then((result) => {
// result.config is the parsed configuration object
// result.filepath is the path to the config file that was found
})
.catch((parsingError) => {
// do something constructive
});
```
The function `cosmiconfig()` searches for a configuration object and returns a Promise,
which resolves with an object containing the information you're looking for.
So let's say `var yourModuleName = 'goldengrahams'` — here's how cosmiconfig will work:
- Starting from `process.cwd()` (or some other directory defined by the `searchPath` argument to `load()`), it looks for configuration objects in three places, in this order:
1. A `goldengrahams` property in a `package.json` file (or some other property defined by `options.packageProp`);
2. A `.goldengrahamsrc` file with JSON or YAML syntax (or some other filename defined by `options.rc`);
3. A `goldengrahams.config.js` JS file exporting the object (or some other filename defined by `options.js`).
- If none of those searches reveal a configuration object, it moves down one directory and tries again. So the search continues in `./`, `../`, `../../`, `../../../`, etc., checking those three locations in each directory.
- It continues searching until it arrives at your home directory (or some other directory defined by `options.stopDir`).
- If at any point a parseable configuration is found, the `cosmiconfig()` Promise resolves with its result object.
- If no configuration object is found, the `cosmiconfig()` Promise resolves with `null`.
- If a configuration object is found *but is malformed* (causing a parsing error), the `cosmiconfig()` Promise rejects and shares that error (so you should `.catch()` it).
All this searching can be short-circuited by passing `options.configPath` or a `--config` CLI argument to specify a file.
cosmiconfig will read that file and try parsing it as JSON, YAML, or JS.
## Caching
As of v2, cosmiconfig uses a few caches to reduce the need for repetitious reading of the filesystem. Every new cosmiconfig instance (created with `cosmiconfig()`) has its own caches.
To avoid or work around caching, you can
- create separate instances of cosmiconfig, or
- set `cache: false` in your options.
- use the cache clearing methods documented below.
## API
### `var explorer = cosmiconfig(moduleName[, options])`
Creates a cosmiconfig instance (i.e. explorer) configured according to the arguments, and initializes its caches.
#### moduleName
Type: `string`
You module name. This is used to create the default filenames that cosmiconfig will look for.
#### Options
##### packageProp
Type: `string` or `false`
Default: `'[moduleName]'`
Name of the property in `package.json` to look for.
If `false`, cosmiconfig will not look in `package.json` files.
##### rc
Type: `string` or `false`
Default: `'.[moduleName]rc'`
Name of the "rc file" to look for, which can be formatted as JSON or YAML.
If `false`, cosmiconfig will not look for an rc file.
If `rcExtensions: true`, the rc file can also have extensions that specify the syntax, e.g. `.[moduleName]rc.json`.
You may like extensions on your rc files because you'll get syntax highlighting and linting in text editors.
Also, with `rcExtensions: true`, you can use JS modules as rc files, e.g. `.[moduleName]rc.js`.
##### js
Type: `string` or `false`
Default: `'[moduleName].config.js'`
Name of a JS file to look for, which must export the configuration object.
If `false`, cosmiconfig will not look for a JS file.
##### argv
Type: `string` or `false`
Default: `'config'`
Name of a `process.argv` argument to look for, whose value should be the path to a configuration file.
cosmiconfig will read the file and try to parse it as JSON, YAML, or JS.
By default, cosmiconfig looks for `--config`.
If `false`, cosmiconfig will not look for any `process.argv` arguments.
##### rcStrictJson
Type: `boolean`
Default: `false`
If `true`, cosmiconfig will expect rc files to be strict JSON. No YAML permitted, and no sloppy JSON.
By default, rc files are parsed with [js-yaml](https://github.com/nodeca/js-yaml), which is
more permissive with punctuation than standard strict JSON.
##### rcExtensions
Type: `boolean`
Default: `false`
If `true`, cosmiconfig will look for rc files with extensions, in addition to rc files without.
This adds a few steps to the search process.
Instead of *just* looking for `.goldengrahamsrc` (no extension), it will also look for the following, in this order:
- `.goldengrahamsrc.json`
- `.goldengrahamsrc.yaml`
- `.goldengrahamsrc.yml`
- `.goldengrahamsrc.js`
##### stopDir
Type: `string`
Default: Absolute path to your home directory
Directory where the search will stop.
##### cache
Type: `boolean`
Default: `true`
If `false`, no caches will be used.
##### transform
Type: `Function` returning a Promise
A function that transforms the parsed configuration. Receives the result object with `config` and `filepath` properties, and must return a Promise that resolves with the transformed result.
The reason you might use this option instead of simply applying your transform function some other way is that *the transformed result will be cached*. If your transformation involves additional filesystem I/O or other potentially slow processing, you can use this option to avoid repeating those steps every time a given configuration is loaded.
### Instance methods (on `explorer`)
#### `load([searchPath, configPath])`
Find and load a configuration file. Returns a Promise that resolves with `null`, if nothing is found, or an object with two properties:
- `config`: The loaded and parsed configuration.
- `filepath`: The filepath where this configuration was found.
You should provide *either* `searchPath` *or* `configPath`. Use `configPath` if you know the path of the configuration file you want to load. Otherwise, use `searchPath`.
```js
explorer.load('start/search/here');
explorer.load('start/search/at/this/file.css');
explorer.load(null, 'load/this/file.json');
```
If you provide `searchPath`, cosmiconfig will start its search at `searchPath` and continue to search up the file tree, as documented above.
If you provide `configPath` (i.e. you already know where the configuration is that you want to load), cosmiconfig will try to read and parse that file.
#### `clearFileCache()`
Clears the cache used when you provide a `configPath` argument to `load`.
#### `clearDirectoryCache()`
Clears the cache used when you provide a `searchPath` argument to `load`.
#### `clearCaches()`
Performs both `clearFileCache()` and `clearDirectoryCache()`.
## Differences from [rc](https://github.com/dominictarr/rc)
[rc](https://github.com/dominictarr/rc) serves its focused purpose well. cosmiconfig differs in a few key ways — making it more useful for some projects, less useful for others:
- Looks for configuration in some different places: in a `package.json` property, an rc file, a `.config.js` file, and rc files with extensions.
- Built-in support for JSON, YAML, and CommonJS formats.
- Stops at the first configuration found, instead of finding all that can be found down the filetree and merging them automatically.
- Options.
- Asynchronicity.
## Contributing & Development
Please note that this project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by its terms.
And please do participate!

View File

@@ -0,0 +1,27 @@
'use strict';
var path = require('path');
var oshomedir = require('os-homedir');
var minimist = require('minimist');
var assign = require('object-assign');
var createExplorer = require('./lib/createExplorer');
var parsedCliArgs = minimist(process.argv);
module.exports = function (moduleName, options) {
options = assign({
packageProp: moduleName,
rc: '.' + moduleName + 'rc',
js: moduleName + '.config.js',
argv: 'config',
rcStrictJson: false,
stopDir: oshomedir(),
cache: true,
}, options);
if (options.argv && parsedCliArgs[options.argv]) {
options.configPath = path.resolve(parsedCliArgs[options.argv]);
}
return createExplorer(options);
};

View File

@@ -0,0 +1,113 @@
'use strict';
var path = require('path');
var isDir = require('is-directory');
var loadPackageProp = require('./loadPackageProp');
var loadRc = require('./loadRc');
var loadJs = require('./loadJs');
var loadDefinedFile = require('./loadDefinedFile');
module.exports = function (options) {
// These cache Promises that resolve with results, not the results themselves
var fileCache = (options.cache) ? new Map() : null;
var directoryCache = (options.cache) ? new Map() : null;
var transform = options.transform || identityPromise;
function clearFileCache() {
if (fileCache) fileCache.clear();
}
function clearDirectoryCache() {
if (directoryCache) directoryCache.clear();
}
function clearCaches() {
clearFileCache();
clearDirectoryCache();
}
function load(searchPath, configPath) {
if (!configPath && options.configPath) {
configPath = options.configPath;
}
if (configPath) {
var absoluteConfigPath = path.resolve(process.cwd(), configPath);
if (fileCache && fileCache.has(absoluteConfigPath)) {
return fileCache.get(absoluteConfigPath);
}
var result = loadDefinedFile(absoluteConfigPath, options)
.then(transform);
if (fileCache) fileCache.set(absoluteConfigPath, result);
return result;
}
if (!searchPath) return Promise.resolve(null);
var absoluteSearchPath = path.resolve(process.cwd(), searchPath);
return isDirectory(absoluteSearchPath)
.then(function (searchPathIsDirectory) {
var directory = (searchPathIsDirectory)
? absoluteSearchPath
: path.dirname(absoluteSearchPath);
return searchDirectory(directory);
});
}
function searchDirectory(directory) {
if (directoryCache && directoryCache.has(directory)) {
return directoryCache.get(directory);
}
var result = Promise.resolve()
.then(function () {
if (!options.packageProp) return;
return loadPackageProp(directory, options);
})
.then(function (result) {
if (result || !options.rc) return result;
return loadRc(path.join(directory, options.rc), options);
})
.then(function (result) {
if (result || !options.js) return result;
return loadJs(path.join(directory, options.js));
})
.then(function (result) {
if (result) return result;
var splitPath = directory.split(path.sep);
var nextDirectory = (splitPath.length > 1)
? splitPath.slice(0, -1).join(path.sep)
: null;
if (!nextDirectory || directory === options.stopDir) return null;
return searchDirectory(nextDirectory);
})
.then(transform);
if (directoryCache) directoryCache.set(directory, result);
return result;
}
return {
load: load,
clearFileCache: clearFileCache,
clearDirectoryCache: clearDirectoryCache,
clearCaches: clearCaches,
};
};
function isDirectory(filepath) {
return new Promise(function (resolve, reject) {
return isDir(filepath, function (err, dir) {
if (err) return reject(err);
return resolve(dir);
});
});
}
function identityPromise(x) {
return Promise.resolve(x);
}

View File

@@ -0,0 +1,66 @@
'use strict';
var yaml = require('js-yaml');
var requireFromString = require('require-from-string');
var readFile = require('./readFile');
var parseJson = require('./parseJson');
module.exports = function (filepath, options) {
return readFile(filepath, { throwNotFound: true }).then(function (content) {
var parsedConfig = (function () {
switch (options.format) {
case 'json':
return parseJson(content, filepath);
case 'yaml':
return yaml.safeLoad(content, {
filename: filepath,
});
case 'js':
return requireFromString(content, filepath);
default:
return tryAllParsing(content, filepath);
}
})();
if (!parsedConfig) {
throw new Error(
'Failed to parse "' + filepath + '" as JSON, JS, or YAML.'
);
}
return {
config: parsedConfig,
filepath: filepath,
};
});
};
function tryAllParsing(content, filepath) {
return tryYaml(content, filepath, function () {
return tryRequire(content, filepath, function () {
return null;
});
});
}
function tryYaml(content, filepath, cb) {
try {
var result = yaml.safeLoad(content, {
filename: filepath,
});
if (typeof result === 'string') {
return cb();
}
return result;
} catch (e) {
return cb();
}
}
function tryRequire(content, filepath, cb) {
try {
return requireFromString(content, filepath);
} catch (e) {
return cb();
}
}

View File

@@ -0,0 +1,15 @@
'use strict';
var requireFromString = require('require-from-string');
var readFile = require('./readFile');
module.exports = function (filepath) {
return readFile(filepath).then(function (content) {
if (!content) return null;
return {
config: requireFromString(content, filepath),
filepath: filepath,
};
});
};

View File

@@ -0,0 +1,21 @@
'use strict';
var path = require('path');
var readFile = require('./readFile');
var parseJson = require('./parseJson');
module.exports = function (packageDir, options) {
var packagePath = path.join(packageDir, 'package.json');
return readFile(packagePath).then(function (content) {
if (!content) return null;
var parsedContent = parseJson(content, packagePath);
var packagePropValue = parsedContent[options.packageProp];
if (!packagePropValue) return null;
return {
config: packagePropValue,
filepath: packagePath,
};
});
};

View File

@@ -0,0 +1,85 @@
'use strict';
var yaml = require('js-yaml');
var requireFromString = require('require-from-string');
var readFile = require('./readFile');
var parseJson = require('./parseJson');
module.exports = function (filepath, options) {
return loadExtensionlessRc().then(function (result) {
if (result) return result;
if (options.rcExtensions) return loadRcWithExtensions();
return null;
});
function loadExtensionlessRc() {
return readRcFile().then(function (content) {
if (!content) return null;
var pasedConfig = (options.rcStrictJson)
? parseJson(content, filepath)
: yaml.safeLoad(content, {
filename: filepath,
});
return {
config: pasedConfig,
filepath: filepath,
};
});
}
function loadRcWithExtensions() {
return readRcFile('json').then(function (content) {
if (content) {
var successFilepath = filepath + '.json';
return {
config: parseJson(content, successFilepath),
filepath: successFilepath,
};
}
// If not content was found in the file with extension,
// try the next possible extension
return readRcFile('yaml');
}).then(function (content) {
if (content) {
// If the previous check returned an object with a config
// property, then it succeeded and this step can be skipped
if (content.config) return content;
// If it just returned a string, then *this* check succeeded
var successFilepath = filepath + '.yaml';
return {
config: yaml.safeLoad(content, { filename: successFilepath }),
filepath: successFilepath,
};
}
return readRcFile('yml');
}).then(function (content) {
if (content) {
if (content.config) return content;
var successFilepath = filepath + '.yml';
return {
config: yaml.safeLoad(content, { filename: successFilepath }),
filepath: successFilepath,
};
}
return readRcFile('js');
}).then(function (content) {
if (content) {
if (content.config) return content;
var successFilepath = filepath + '.js';
return {
config: requireFromString(content, successFilepath),
filepath: successFilepath,
};
}
return null;
});
}
function readRcFile(extension) {
var filepathWithExtension = (extension)
? filepath + '.' + extension
: filepath;
return readFile(filepathWithExtension);
}
};

View File

@@ -0,0 +1,12 @@
'use strict';
var parseJson = require('parse-json');
module.exports = function (json, filepath) {
try {
return parseJson(json);
} catch (err) {
err.message = 'JSON Error in ' + filepath + ':\n' + err.message;
throw err;
}
};

View File

@@ -0,0 +1,20 @@
'use strict';
var fs = require('fs');
module.exports = function (filepath, options) {
options = options || {};
options.throwNotFound = options.throwNotFound || false;
return new Promise(function (resolve, reject) {
fs.readFile(filepath, 'utf8', function (err, content) {
if (err && err.code === 'ENOENT' && !options.throwNotFound) {
return resolve(null);
}
if (err) return reject(err);
resolve(content);
});
});
};

View File

@@ -0,0 +1,89 @@
{
"_from": "cosmiconfig@^2.1.0",
"_id": "cosmiconfig@2.2.2",
"_inBundle": false,
"_integrity": "sha512-GiNXLwAFPYHy25XmTPpafYvn3CLAkJ8FLsscq78MQd1Kh0OU6Yzhn4eV2MVF4G9WEQZoWEGltatdR+ntGPMl5A==",
"_location": "/vue-loader/cosmiconfig",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "cosmiconfig@^2.1.0",
"name": "cosmiconfig",
"escapedName": "cosmiconfig",
"rawSpec": "^2.1.0",
"saveSpec": null,
"fetchSpec": "^2.1.0"
},
"_requiredBy": [
"/vue-loader/postcss-load-config"
],
"_resolved": "https://registry.npmjs.org/cosmiconfig/-/cosmiconfig-2.2.2.tgz",
"_shasum": "6173cebd56fac042c1f4390edf7af6c07c7cb892",
"_spec": "cosmiconfig@^2.1.0",
"_where": "C:\\xampp\\htdocs\\w4rpservices\\node_modules\\vue-loader\\node_modules\\postcss-load-config",
"author": {
"name": "David Clark",
"email": "david.dave.clark@gmail.com"
},
"bugs": {
"url": "https://github.com/davidtheclark/cosmiconfig/issues"
},
"bundleDependencies": false,
"contributors": [
{
"name": "Bogdan Chadkin",
"email": "trysound@yandex.ru"
}
],
"dependencies": {
"is-directory": "^0.3.1",
"js-yaml": "^3.4.3",
"minimist": "^1.2.0",
"object-assign": "^4.1.0",
"os-homedir": "^1.0.1",
"parse-json": "^2.2.0",
"require-from-string": "^1.1.0"
},
"deprecated": false,
"description": "Find and load configuration from a package.json property, rc file, or CommonJS module",
"devDependencies": {
"eslint": "^3.13.0",
"eslint-config-davidtheclark-node": "^0.2.0",
"eslint-plugin-node": "^3.0.5",
"expect": "^1.20.2",
"lodash": "^4.17.4",
"node-version-check": "^2.1.1",
"nyc": "^10.0.0",
"sinon": "^1.17.7",
"tap-spec": "^4.1.1",
"tape": "^4.6.3"
},
"engines": {
"node": ">=0.12"
},
"files": [
"index.js",
"lib"
],
"homepage": "https://github.com/davidtheclark/cosmiconfig#readme",
"keywords": [
"load",
"configuration",
"config"
],
"license": "MIT",
"main": "index.js",
"name": "cosmiconfig",
"repository": {
"type": "git",
"url": "git+https://github.com/davidtheclark/cosmiconfig.git"
},
"scripts": {
"coverage": "nyc npm run tape && nyc report --reporter=html && open coverage/index.html",
"lint": "node-version-gte-4 && eslint . || echo \"ESLint not supported\"",
"tape": "tape test/*.test.js | tap-spec",
"test": "npm run tape && npm run lint"
},
"version": "2.2.2"
}

View File

@@ -0,0 +1,8 @@
language: node_js
node_js:
- "0.8"
- "0.10"
- "0.12"
- "iojs"
before_install:
- npm install -g npm@~1.4.6

18
node_modules/vue-loader/node_modules/minimist/LICENSE generated vendored Normal file
View File

@@ -0,0 +1,18 @@
This software is released under the MIT license:
Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
the Software, and to permit persons to whom the Software is furnished to do so,
subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,2 @@
var argv = require('../')(process.argv.slice(2));
console.dir(argv);

236
node_modules/vue-loader/node_modules/minimist/index.js generated vendored Normal file
View File

@@ -0,0 +1,236 @@
module.exports = function (args, opts) {
if (!opts) opts = {};
var flags = { bools : {}, strings : {}, unknownFn: null };
if (typeof opts['unknown'] === 'function') {
flags.unknownFn = opts['unknown'];
}
if (typeof opts['boolean'] === 'boolean' && opts['boolean']) {
flags.allBools = true;
} else {
[].concat(opts['boolean']).filter(Boolean).forEach(function (key) {
flags.bools[key] = true;
});
}
var aliases = {};
Object.keys(opts.alias || {}).forEach(function (key) {
aliases[key] = [].concat(opts.alias[key]);
aliases[key].forEach(function (x) {
aliases[x] = [key].concat(aliases[key].filter(function (y) {
return x !== y;
}));
});
});
[].concat(opts.string).filter(Boolean).forEach(function (key) {
flags.strings[key] = true;
if (aliases[key]) {
flags.strings[aliases[key]] = true;
}
});
var defaults = opts['default'] || {};
var argv = { _ : [] };
Object.keys(flags.bools).forEach(function (key) {
setArg(key, defaults[key] === undefined ? false : defaults[key]);
});
var notFlags = [];
if (args.indexOf('--') !== -1) {
notFlags = args.slice(args.indexOf('--')+1);
args = args.slice(0, args.indexOf('--'));
}
function argDefined(key, arg) {
return (flags.allBools && /^--[^=]+$/.test(arg)) ||
flags.strings[key] || flags.bools[key] || aliases[key];
}
function setArg (key, val, arg) {
if (arg && flags.unknownFn && !argDefined(key, arg)) {
if (flags.unknownFn(arg) === false) return;
}
var value = !flags.strings[key] && isNumber(val)
? Number(val) : val
;
setKey(argv, key.split('.'), value);
(aliases[key] || []).forEach(function (x) {
setKey(argv, x.split('.'), value);
});
}
function setKey (obj, keys, value) {
var o = obj;
keys.slice(0,-1).forEach(function (key) {
if (o[key] === undefined) o[key] = {};
o = o[key];
});
var key = keys[keys.length - 1];
if (o[key] === undefined || flags.bools[key] || typeof o[key] === 'boolean') {
o[key] = value;
}
else if (Array.isArray(o[key])) {
o[key].push(value);
}
else {
o[key] = [ o[key], value ];
}
}
function aliasIsBoolean(key) {
return aliases[key].some(function (x) {
return flags.bools[x];
});
}
for (var i = 0; i < args.length; i++) {
var arg = args[i];
if (/^--.+=/.test(arg)) {
// Using [\s\S] instead of . because js doesn't support the
// 'dotall' regex modifier. See:
// http://stackoverflow.com/a/1068308/13216
var m = arg.match(/^--([^=]+)=([\s\S]*)$/);
var key = m[1];
var value = m[2];
if (flags.bools[key]) {
value = value !== 'false';
}
setArg(key, value, arg);
}
else if (/^--no-.+/.test(arg)) {
var key = arg.match(/^--no-(.+)/)[1];
setArg(key, false, arg);
}
else if (/^--.+/.test(arg)) {
var key = arg.match(/^--(.+)/)[1];
var next = args[i + 1];
if (next !== undefined && !/^-/.test(next)
&& !flags.bools[key]
&& !flags.allBools
&& (aliases[key] ? !aliasIsBoolean(key) : true)) {
setArg(key, next, arg);
i++;
}
else if (/^(true|false)$/.test(next)) {
setArg(key, next === 'true', arg);
i++;
}
else {
setArg(key, flags.strings[key] ? '' : true, arg);
}
}
else if (/^-[^-]+/.test(arg)) {
var letters = arg.slice(1,-1).split('');
var broken = false;
for (var j = 0; j < letters.length; j++) {
var next = arg.slice(j+2);
if (next === '-') {
setArg(letters[j], next, arg)
continue;
}
if (/[A-Za-z]/.test(letters[j]) && /=/.test(next)) {
setArg(letters[j], next.split('=')[1], arg);
broken = true;
break;
}
if (/[A-Za-z]/.test(letters[j])
&& /-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) {
setArg(letters[j], next, arg);
broken = true;
break;
}
if (letters[j+1] && letters[j+1].match(/\W/)) {
setArg(letters[j], arg.slice(j+2), arg);
broken = true;
break;
}
else {
setArg(letters[j], flags.strings[letters[j]] ? '' : true, arg);
}
}
var key = arg.slice(-1)[0];
if (!broken && key !== '-') {
if (args[i+1] && !/^(-|--)[^-]/.test(args[i+1])
&& !flags.bools[key]
&& (aliases[key] ? !aliasIsBoolean(key) : true)) {
setArg(key, args[i+1], arg);
i++;
}
else if (args[i+1] && /true|false/.test(args[i+1])) {
setArg(key, args[i+1] === 'true', arg);
i++;
}
else {
setArg(key, flags.strings[key] ? '' : true, arg);
}
}
}
else {
if (!flags.unknownFn || flags.unknownFn(arg) !== false) {
argv._.push(
flags.strings['_'] || !isNumber(arg) ? arg : Number(arg)
);
}
if (opts.stopEarly) {
argv._.push.apply(argv._, args.slice(i + 1));
break;
}
}
}
Object.keys(defaults).forEach(function (key) {
if (!hasKey(argv, key.split('.'))) {
setKey(argv, key.split('.'), defaults[key]);
(aliases[key] || []).forEach(function (x) {
setKey(argv, x.split('.'), defaults[key]);
});
}
});
if (opts['--']) {
argv['--'] = new Array();
notFlags.forEach(function(key) {
argv['--'].push(key);
});
}
else {
notFlags.forEach(function(key) {
argv._.push(key);
});
}
return argv;
};
function hasKey (obj, keys) {
var o = obj;
keys.slice(0,-1).forEach(function (key) {
o = (o[key] || {});
});
var key = keys[keys.length - 1];
return key in o;
}
function isNumber (x) {
if (typeof x === 'number') return true;
if (/^0x[0-9a-f]+$/i.test(x)) return true;
return /^[-+]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x);
}

View File

@@ -0,0 +1,73 @@
{
"_from": "minimist@^1.2.0",
"_id": "minimist@1.2.0",
"_inBundle": false,
"_integrity": "sha1-o1AIsg9BOD7sH7kU9M1d95omQoQ=",
"_location": "/vue-loader/minimist",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "minimist@^1.2.0",
"name": "minimist",
"escapedName": "minimist",
"rawSpec": "^1.2.0",
"saveSpec": null,
"fetchSpec": "^1.2.0"
},
"_requiredBy": [
"/vue-loader/cosmiconfig"
],
"_resolved": "http://registry.npmjs.org/minimist/-/minimist-1.2.0.tgz",
"_shasum": "a35008b20f41383eec1fb914f4cd5df79a264284",
"_spec": "minimist@^1.2.0",
"_where": "C:\\xampp\\htdocs\\w4rpservices\\node_modules\\vue-loader\\node_modules\\cosmiconfig",
"author": {
"name": "James Halliday",
"email": "mail@substack.net",
"url": "http://substack.net"
},
"bugs": {
"url": "https://github.com/substack/minimist/issues"
},
"bundleDependencies": false,
"deprecated": false,
"description": "parse argument options",
"devDependencies": {
"covert": "^1.0.0",
"tap": "~0.4.0",
"tape": "^3.5.0"
},
"homepage": "https://github.com/substack/minimist",
"keywords": [
"argv",
"getopt",
"parser",
"optimist"
],
"license": "MIT",
"main": "index.js",
"name": "minimist",
"repository": {
"type": "git",
"url": "git://github.com/substack/minimist.git"
},
"scripts": {
"coverage": "covert test/*.js",
"test": "tap test/*.js"
},
"testling": {
"files": "test/*.js",
"browsers": [
"ie/6..latest",
"ff/5",
"firefox/latest",
"chrome/10",
"chrome/latest",
"safari/5.1",
"safari/latest",
"opera/12"
]
},
"version": "1.2.0"
}

View File

@@ -0,0 +1,91 @@
# minimist
parse argument options
This module is the guts of optimist's argument parser without all the
fanciful decoration.
[![browser support](https://ci.testling.com/substack/minimist.png)](http://ci.testling.com/substack/minimist)
[![build status](https://secure.travis-ci.org/substack/minimist.png)](http://travis-ci.org/substack/minimist)
# example
``` js
var argv = require('minimist')(process.argv.slice(2));
console.dir(argv);
```
```
$ node example/parse.js -a beep -b boop
{ _: [], a: 'beep', b: 'boop' }
```
```
$ node example/parse.js -x 3 -y 4 -n5 -abc --beep=boop foo bar baz
{ _: [ 'foo', 'bar', 'baz' ],
x: 3,
y: 4,
n: 5,
a: true,
b: true,
c: true,
beep: 'boop' }
```
# methods
``` js
var parseArgs = require('minimist')
```
## var argv = parseArgs(args, opts={})
Return an argument object `argv` populated with the array arguments from `args`.
`argv._` contains all the arguments that didn't have an option associated with
them.
Numeric-looking arguments will be returned as numbers unless `opts.string` or
`opts.boolean` is set for that argument name.
Any arguments after `'--'` will not be parsed and will end up in `argv._`.
options can be:
* `opts.string` - a string or array of strings argument names to always treat as
strings
* `opts.boolean` - a boolean, string or array of strings to always treat as
booleans. if `true` will treat all double hyphenated arguments without equal signs
as boolean (e.g. affects `--foo`, not `-f` or `--foo=bar`)
* `opts.alias` - an object mapping string names to strings or arrays of string
argument names to use as aliases
* `opts.default` - an object mapping string argument names to default values
* `opts.stopEarly` - when true, populate `argv._` with everything after the
first non-option
* `opts['--']` - when true, populate `argv._` with everything before the `--`
and `argv['--']` with everything after the `--`. Here's an example:
* `opts.unknown` - a function which is invoked with a command line parameter not
defined in the `opts` configuration object. If the function returns `false`, the
unknown option is not added to `argv`.
```
> require('./')('one two three -- four five --six'.split(' '), { '--': true })
{ _: [ 'one', 'two', 'three' ],
'--': [ 'four', 'five', '--six' ] }
```
Note that with `opts['--']` set, parsing for arguments still stops after the
`--`.
# install
With [npm](https://npmjs.org) do:
```
npm install minimist
```
# license
MIT

View File

@@ -0,0 +1,32 @@
var parse = require('../');
var test = require('tape');
test('flag boolean true (default all --args to boolean)', function (t) {
var argv = parse(['moo', '--honk', 'cow'], {
boolean: true
});
t.deepEqual(argv, {
honk: true,
_: ['moo', 'cow']
});
t.deepEqual(typeof argv.honk, 'boolean');
t.end();
});
test('flag boolean true only affects double hyphen arguments without equals signs', function (t) {
var argv = parse(['moo', '--honk', 'cow', '-p', '55', '--tacos=good'], {
boolean: true
});
t.deepEqual(argv, {
honk: true,
tacos: 'good',
p: 55,
_: ['moo', 'cow']
});
t.deepEqual(typeof argv.honk, 'boolean');
t.end();
});

View File

@@ -0,0 +1,166 @@
var parse = require('../');
var test = require('tape');
test('flag boolean default false', function (t) {
var argv = parse(['moo'], {
boolean: ['t', 'verbose'],
default: { verbose: false, t: false }
});
t.deepEqual(argv, {
verbose: false,
t: false,
_: ['moo']
});
t.deepEqual(typeof argv.verbose, 'boolean');
t.deepEqual(typeof argv.t, 'boolean');
t.end();
});
test('boolean groups', function (t) {
var argv = parse([ '-x', '-z', 'one', 'two', 'three' ], {
boolean: ['x','y','z']
});
t.deepEqual(argv, {
x : true,
y : false,
z : true,
_ : [ 'one', 'two', 'three' ]
});
t.deepEqual(typeof argv.x, 'boolean');
t.deepEqual(typeof argv.y, 'boolean');
t.deepEqual(typeof argv.z, 'boolean');
t.end();
});
test('boolean and alias with chainable api', function (t) {
var aliased = [ '-h', 'derp' ];
var regular = [ '--herp', 'derp' ];
var opts = {
herp: { alias: 'h', boolean: true }
};
var aliasedArgv = parse(aliased, {
boolean: 'herp',
alias: { h: 'herp' }
});
var propertyArgv = parse(regular, {
boolean: 'herp',
alias: { h: 'herp' }
});
var expected = {
herp: true,
h: true,
'_': [ 'derp' ]
};
t.same(aliasedArgv, expected);
t.same(propertyArgv, expected);
t.end();
});
test('boolean and alias with options hash', function (t) {
var aliased = [ '-h', 'derp' ];
var regular = [ '--herp', 'derp' ];
var opts = {
alias: { 'h': 'herp' },
boolean: 'herp'
};
var aliasedArgv = parse(aliased, opts);
var propertyArgv = parse(regular, opts);
var expected = {
herp: true,
h: true,
'_': [ 'derp' ]
};
t.same(aliasedArgv, expected);
t.same(propertyArgv, expected);
t.end();
});
test('boolean and alias array with options hash', function (t) {
var aliased = [ '-h', 'derp' ];
var regular = [ '--herp', 'derp' ];
var alt = [ '--harp', 'derp' ];
var opts = {
alias: { 'h': ['herp', 'harp'] },
boolean: 'h'
};
var aliasedArgv = parse(aliased, opts);
var propertyArgv = parse(regular, opts);
var altPropertyArgv = parse(alt, opts);
var expected = {
harp: true,
herp: true,
h: true,
'_': [ 'derp' ]
};
t.same(aliasedArgv, expected);
t.same(propertyArgv, expected);
t.same(altPropertyArgv, expected);
t.end();
});
test('boolean and alias using explicit true', function (t) {
var aliased = [ '-h', 'true' ];
var regular = [ '--herp', 'true' ];
var opts = {
alias: { h: 'herp' },
boolean: 'h'
};
var aliasedArgv = parse(aliased, opts);
var propertyArgv = parse(regular, opts);
var expected = {
herp: true,
h: true,
'_': [ ]
};
t.same(aliasedArgv, expected);
t.same(propertyArgv, expected);
t.end();
});
// regression, see https://github.com/substack/node-optimist/issues/71
test('boolean and --x=true', function(t) {
var parsed = parse(['--boool', '--other=true'], {
boolean: 'boool'
});
t.same(parsed.boool, true);
t.same(parsed.other, 'true');
parsed = parse(['--boool', '--other=false'], {
boolean: 'boool'
});
t.same(parsed.boool, true);
t.same(parsed.other, 'false');
t.end();
});
test('boolean --boool=true', function (t) {
var parsed = parse(['--boool=true'], {
default: {
boool: false
},
boolean: ['boool']
});
t.same(parsed.boool, true);
t.end();
});
test('boolean --boool=false', function (t) {
var parsed = parse(['--boool=false'], {
default: {
boool: true
},
boolean: ['boool']
});
t.same(parsed.boool, false);
t.end();
});

View File

@@ -0,0 +1,31 @@
var parse = require('../');
var test = require('tape');
test('-', function (t) {
t.plan(5);
t.deepEqual(parse([ '-n', '-' ]), { n: '-', _: [] });
t.deepEqual(parse([ '-' ]), { _: [ '-' ] });
t.deepEqual(parse([ '-f-' ]), { f: '-', _: [] });
t.deepEqual(
parse([ '-b', '-' ], { boolean: 'b' }),
{ b: true, _: [ '-' ] }
);
t.deepEqual(
parse([ '-s', '-' ], { string: 's' }),
{ s: '-', _: [] }
);
});
test('-a -- b', function (t) {
t.plan(3);
t.deepEqual(parse([ '-a', '--', 'b' ]), { a: true, _: [ 'b' ] });
t.deepEqual(parse([ '--a', '--', 'b' ]), { a: true, _: [ 'b' ] });
t.deepEqual(parse([ '--a', '--', 'b' ]), { a: true, _: [ 'b' ] });
});
test('move arguments after the -- into their own `--` array', function(t) {
t.plan(1);
t.deepEqual(
parse([ '--name', 'John', 'before', '--', 'after' ], { '--': true }),
{ name: 'John', _: [ 'before' ], '--': [ 'after' ] });
});

View File

@@ -0,0 +1,35 @@
var test = require('tape');
var parse = require('../');
test('boolean default true', function (t) {
var argv = parse([], {
boolean: 'sometrue',
default: { sometrue: true }
});
t.equal(argv.sometrue, true);
t.end();
});
test('boolean default false', function (t) {
var argv = parse([], {
boolean: 'somefalse',
default: { somefalse: false }
});
t.equal(argv.somefalse, false);
t.end();
});
test('boolean default to null', function (t) {
var argv = parse([], {
boolean: 'maybe',
default: { maybe: null }
});
t.equal(argv.maybe, null);
var argv = parse(['--maybe'], {
boolean: 'maybe',
default: { maybe: null }
});
t.equal(argv.maybe, true);
t.end();
})

View File

@@ -0,0 +1,22 @@
var parse = require('../');
var test = require('tape');
test('dotted alias', function (t) {
var argv = parse(['--a.b', '22'], {default: {'a.b': 11}, alias: {'a.b': 'aa.bb'}});
t.equal(argv.a.b, 22);
t.equal(argv.aa.bb, 22);
t.end();
});
test('dotted default', function (t) {
var argv = parse('', {default: {'a.b': 11}, alias: {'a.b': 'aa.bb'}});
t.equal(argv.a.b, 11);
t.equal(argv.aa.bb, 11);
t.end();
});
test('dotted default with no alias', function (t) {
var argv = parse('', {default: {'a.b': 11}});
t.equal(argv.a.b, 11);
t.end();
});

View File

@@ -0,0 +1,16 @@
var parse = require('../');
var test = require('tape');
test('short -k=v' , function (t) {
t.plan(1);
var argv = parse([ '-b=123' ]);
t.deepEqual(argv, { b: 123, _: [] });
});
test('multi short -k=v' , function (t) {
t.plan(1);
var argv = parse([ '-a=whatever', '-b=robots' ]);
t.deepEqual(argv, { a: 'whatever', b: 'robots', _: [] });
});

View File

@@ -0,0 +1,31 @@
var test = require('tape');
var parse = require('../');
test('long opts', function (t) {
t.deepEqual(
parse([ '--bool' ]),
{ bool : true, _ : [] },
'long boolean'
);
t.deepEqual(
parse([ '--pow', 'xixxle' ]),
{ pow : 'xixxle', _ : [] },
'long capture sp'
);
t.deepEqual(
parse([ '--pow=xixxle' ]),
{ pow : 'xixxle', _ : [] },
'long capture eq'
);
t.deepEqual(
parse([ '--host', 'localhost', '--port', '555' ]),
{ host : 'localhost', port : 555, _ : [] },
'long captures sp'
);
t.deepEqual(
parse([ '--host=localhost', '--port=555' ]),
{ host : 'localhost', port : 555, _ : [] },
'long captures eq'
);
t.end();
});

View File

@@ -0,0 +1,36 @@
var parse = require('../');
var test = require('tape');
test('nums', function (t) {
var argv = parse([
'-x', '1234',
'-y', '5.67',
'-z', '1e7',
'-w', '10f',
'--hex', '0xdeadbeef',
'789'
]);
t.deepEqual(argv, {
x : 1234,
y : 5.67,
z : 1e7,
w : '10f',
hex : 0xdeadbeef,
_ : [ 789 ]
});
t.deepEqual(typeof argv.x, 'number');
t.deepEqual(typeof argv.y, 'number');
t.deepEqual(typeof argv.z, 'number');
t.deepEqual(typeof argv.w, 'string');
t.deepEqual(typeof argv.hex, 'number');
t.deepEqual(typeof argv._[0], 'number');
t.end();
});
test('already a number', function (t) {
var argv = parse([ '-x', 1234, 789 ]);
t.deepEqual(argv, { x : 1234, _ : [ 789 ] });
t.deepEqual(typeof argv.x, 'number');
t.deepEqual(typeof argv._[0], 'number');
t.end();
});

View File

@@ -0,0 +1,197 @@
var parse = require('../');
var test = require('tape');
test('parse args', function (t) {
t.deepEqual(
parse([ '--no-moo' ]),
{ moo : false, _ : [] },
'no'
);
t.deepEqual(
parse([ '-v', 'a', '-v', 'b', '-v', 'c' ]),
{ v : ['a','b','c'], _ : [] },
'multi'
);
t.end();
});
test('comprehensive', function (t) {
t.deepEqual(
parse([
'--name=meowmers', 'bare', '-cats', 'woo',
'-h', 'awesome', '--multi=quux',
'--key', 'value',
'-b', '--bool', '--no-meep', '--multi=baz',
'--', '--not-a-flag', 'eek'
]),
{
c : true,
a : true,
t : true,
s : 'woo',
h : 'awesome',
b : true,
bool : true,
key : 'value',
multi : [ 'quux', 'baz' ],
meep : false,
name : 'meowmers',
_ : [ 'bare', '--not-a-flag', 'eek' ]
}
);
t.end();
});
test('flag boolean', function (t) {
var argv = parse([ '-t', 'moo' ], { boolean: 't' });
t.deepEqual(argv, { t : true, _ : [ 'moo' ] });
t.deepEqual(typeof argv.t, 'boolean');
t.end();
});
test('flag boolean value', function (t) {
var argv = parse(['--verbose', 'false', 'moo', '-t', 'true'], {
boolean: [ 't', 'verbose' ],
default: { verbose: true }
});
t.deepEqual(argv, {
verbose: false,
t: true,
_: ['moo']
});
t.deepEqual(typeof argv.verbose, 'boolean');
t.deepEqual(typeof argv.t, 'boolean');
t.end();
});
test('newlines in params' , function (t) {
var args = parse([ '-s', "X\nX" ])
t.deepEqual(args, { _ : [], s : "X\nX" });
// reproduce in bash:
// VALUE="new
// line"
// node program.js --s="$VALUE"
args = parse([ "--s=X\nX" ])
t.deepEqual(args, { _ : [], s : "X\nX" });
t.end();
});
test('strings' , function (t) {
var s = parse([ '-s', '0001234' ], { string: 's' }).s;
t.equal(s, '0001234');
t.equal(typeof s, 'string');
var x = parse([ '-x', '56' ], { string: 'x' }).x;
t.equal(x, '56');
t.equal(typeof x, 'string');
t.end();
});
test('stringArgs', function (t) {
var s = parse([ ' ', ' ' ], { string: '_' })._;
t.same(s.length, 2);
t.same(typeof s[0], 'string');
t.same(s[0], ' ');
t.same(typeof s[1], 'string');
t.same(s[1], ' ');
t.end();
});
test('empty strings', function(t) {
var s = parse([ '-s' ], { string: 's' }).s;
t.equal(s, '');
t.equal(typeof s, 'string');
var str = parse([ '--str' ], { string: 'str' }).str;
t.equal(str, '');
t.equal(typeof str, 'string');
var letters = parse([ '-art' ], {
string: [ 'a', 't' ]
});
t.equal(letters.a, '');
t.equal(letters.r, true);
t.equal(letters.t, '');
t.end();
});
test('string and alias', function(t) {
var x = parse([ '--str', '000123' ], {
string: 's',
alias: { s: 'str' }
});
t.equal(x.str, '000123');
t.equal(typeof x.str, 'string');
t.equal(x.s, '000123');
t.equal(typeof x.s, 'string');
var y = parse([ '-s', '000123' ], {
string: 'str',
alias: { str: 's' }
});
t.equal(y.str, '000123');
t.equal(typeof y.str, 'string');
t.equal(y.s, '000123');
t.equal(typeof y.s, 'string');
t.end();
});
test('slashBreak', function (t) {
t.same(
parse([ '-I/foo/bar/baz' ]),
{ I : '/foo/bar/baz', _ : [] }
);
t.same(
parse([ '-xyz/foo/bar/baz' ]),
{ x : true, y : true, z : '/foo/bar/baz', _ : [] }
);
t.end();
});
test('alias', function (t) {
var argv = parse([ '-f', '11', '--zoom', '55' ], {
alias: { z: 'zoom' }
});
t.equal(argv.zoom, 55);
t.equal(argv.z, argv.zoom);
t.equal(argv.f, 11);
t.end();
});
test('multiAlias', function (t) {
var argv = parse([ '-f', '11', '--zoom', '55' ], {
alias: { z: [ 'zm', 'zoom' ] }
});
t.equal(argv.zoom, 55);
t.equal(argv.z, argv.zoom);
t.equal(argv.z, argv.zm);
t.equal(argv.f, 11);
t.end();
});
test('nested dotted objects', function (t) {
var argv = parse([
'--foo.bar', '3', '--foo.baz', '4',
'--foo.quux.quibble', '5', '--foo.quux.o_O',
'--beep.boop'
]);
t.same(argv.foo, {
bar : 3,
baz : 4,
quux : {
quibble : 5,
o_O : true
}
});
t.same(argv.beep, { boop : true });
t.end();
});

View File

@@ -0,0 +1,9 @@
var parse = require('../');
var test = require('tape');
test('parse with modifier functions' , function (t) {
t.plan(1);
var argv = parse([ '-b', '123' ], { boolean: 'b' });
t.deepEqual(argv, { b: true, _: [123] });
});

View File

@@ -0,0 +1,67 @@
var parse = require('../');
var test = require('tape');
test('numeric short args', function (t) {
t.plan(2);
t.deepEqual(parse([ '-n123' ]), { n: 123, _: [] });
t.deepEqual(
parse([ '-123', '456' ]),
{ 1: true, 2: true, 3: 456, _: [] }
);
});
test('short', function (t) {
t.deepEqual(
parse([ '-b' ]),
{ b : true, _ : [] },
'short boolean'
);
t.deepEqual(
parse([ 'foo', 'bar', 'baz' ]),
{ _ : [ 'foo', 'bar', 'baz' ] },
'bare'
);
t.deepEqual(
parse([ '-cats' ]),
{ c : true, a : true, t : true, s : true, _ : [] },
'group'
);
t.deepEqual(
parse([ '-cats', 'meow' ]),
{ c : true, a : true, t : true, s : 'meow', _ : [] },
'short group next'
);
t.deepEqual(
parse([ '-h', 'localhost' ]),
{ h : 'localhost', _ : [] },
'short capture'
);
t.deepEqual(
parse([ '-h', 'localhost', '-p', '555' ]),
{ h : 'localhost', p : 555, _ : [] },
'short captures'
);
t.end();
});
test('mixed short bool and capture', function (t) {
t.same(
parse([ '-h', 'localhost', '-fp', '555', 'script.js' ]),
{
f : true, p : 555, h : 'localhost',
_ : [ 'script.js' ]
}
);
t.end();
});
test('short and long', function (t) {
t.deepEqual(
parse([ '-h', 'localhost', '-fp', '555', 'script.js' ]),
{
f : true, p : 555, h : 'localhost',
_ : [ 'script.js' ]
}
);
t.end();
});

View File

@@ -0,0 +1,15 @@
var parse = require('../');
var test = require('tape');
test('stops parsing on the first non-option when stopEarly is set', function (t) {
var argv = parse(['--aaa', 'bbb', 'ccc', '--ddd'], {
stopEarly: true
});
t.deepEqual(argv, {
aaa: 'bbb',
_: ['ccc', '--ddd']
});
t.end();
});

View File

@@ -0,0 +1,102 @@
var parse = require('../');
var test = require('tape');
test('boolean and alias is not unknown', function (t) {
var unknown = [];
function unknownFn(arg) {
unknown.push(arg);
return false;
}
var aliased = [ '-h', 'true', '--derp', 'true' ];
var regular = [ '--herp', 'true', '-d', 'true' ];
var opts = {
alias: { h: 'herp' },
boolean: 'h',
unknown: unknownFn
};
var aliasedArgv = parse(aliased, opts);
var propertyArgv = parse(regular, opts);
t.same(unknown, ['--derp', '-d']);
t.end();
});
test('flag boolean true any double hyphen argument is not unknown', function (t) {
var unknown = [];
function unknownFn(arg) {
unknown.push(arg);
return false;
}
var argv = parse(['--honk', '--tacos=good', 'cow', '-p', '55'], {
boolean: true,
unknown: unknownFn
});
t.same(unknown, ['--tacos=good', 'cow', '-p']);
t.same(argv, {
honk: true,
_: []
});
t.end();
});
test('string and alias is not unknown', function (t) {
var unknown = [];
function unknownFn(arg) {
unknown.push(arg);
return false;
}
var aliased = [ '-h', 'hello', '--derp', 'goodbye' ];
var regular = [ '--herp', 'hello', '-d', 'moon' ];
var opts = {
alias: { h: 'herp' },
string: 'h',
unknown: unknownFn
};
var aliasedArgv = parse(aliased, opts);
var propertyArgv = parse(regular, opts);
t.same(unknown, ['--derp', '-d']);
t.end();
});
test('default and alias is not unknown', function (t) {
var unknown = [];
function unknownFn(arg) {
unknown.push(arg);
return false;
}
var aliased = [ '-h', 'hello' ];
var regular = [ '--herp', 'hello' ];
var opts = {
default: { 'h': 'bar' },
alias: { 'h': 'herp' },
unknown: unknownFn
};
var aliasedArgv = parse(aliased, opts);
var propertyArgv = parse(regular, opts);
t.same(unknown, []);
t.end();
unknownFn(); // exercise fn for 100% coverage
});
test('value following -- is not unknown', function (t) {
var unknown = [];
function unknownFn(arg) {
unknown.push(arg);
return false;
}
var aliased = [ '--bad', '--', 'good', 'arg' ];
var opts = {
'--': true,
unknown: unknownFn
};
var argv = parse(aliased, opts);
t.same(unknown, ['--bad']);
t.same(argv, {
'--': ['good', 'arg'],
'_': []
})
t.end();
});

View File

@@ -0,0 +1,8 @@
var parse = require('../');
var test = require('tape');
test('whitespace should be whitespace' , function (t) {
t.plan(1);
var x = parse([ '-x', '\t' ]).x;
t.equal(x, '\t');
});

View File

@@ -0,0 +1,33 @@
<a name="1.2.0"></a>
# [1.2.0](https://github.com/michael-ciniawsky/postcss-load-config/compare/v1.1.0...v1.2.0) (2017-02-13)
### Features
* **index:** allow extensions for .postcssrc ([0d3bf35](https://github.com/michael-ciniawsky/postcss-load-config/commit/0d3bf35))
<a name="1.1.0"></a>
# [1.1.0](https://github.com/michael-ciniawsky/postcss-load-config/compare/v1.0.0...v1.1.0) (2017-01-11)
### Features
* **index:** config.file, improve error handling ([a6c32fd](https://github.com/michael-ciniawsky/postcss-load-config/commit/a6c32fd))
<a name="1.0.0"></a>
# [1.0.0]((https://github.com/michael-ciniawsky/postcss-load-config/compare/v1.0.0-rc...1.0.0)) (2016-10-27)
### Bug Fixes
* **index:** behavior when config loading fails ([b549bc6](https://github.com/michael-ciniawsky/postcss-load-config/commit/b549bc6)), closes [#26](https://github.com/michael-ciniawsky/postcss-load-config/issues/26)
* **index:** set NODE_ENV when undefined ([b24501c](https://github.com/michael-ciniawsky/postcss-load-config/commit/b24501c))
* **index:** support node v0.12 ([0bbfa94](https://github.com/michael-ciniawsky/postcss-load-config/commit/0bbfa94))
### Features
* **index:** function support, jsdoc, cleanups ([a78c580](https://github.com/michael-ciniawsky/postcss-load-config/commit/a78c580))

View File

@@ -0,0 +1,21 @@
License (MIT)
Copyright (c) Michael Ciniawsky <michael.ciniawsky@gmail.com>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.

View File

@@ -0,0 +1,405 @@
[![npm][npm]][npm-url]
[![node][node]][node-url]
[![deps][deps]][deps-url]
[![tests][tests]][tests-url]
[![coverage][cover]][cover-url]
[![code style][style]][style-url]
[![chat][chat]][chat-url]
<div align="center">
<img width="100" height="100" title="Load Options" src="http://michael-ciniawsky.github.io/postcss-load-options/logo.svg">
<a href="https://github.com/postcss/postcss">
<img width="110" height="110" title="PostCSS" src="http://postcss.github.io/postcss/logo.svg" hspace="10">
</a>
<img width="100" height="100" title="Load Plugins" src="http://michael-ciniawsky.github.io/postcss-load-plugins/logo.svg">
<h1>Load Config</h1>
</div>
<h2 align="center">Install</h2>
```bash
npm i -D postcss-load-config
```
<h2 align="center">Usage</h2>
```
npm i -S|-D postcss-plugin
```
Install plugins and save them to your ***package.json*** dependencies/devDependencies.
### `package.json`
Create **`postcss`** section in your projects **`package.json`**.
```
App
| client
| public
|
|- package.json
```
```json
{
"postcss": {
"parser": "sugarss",
"map": false,
"from": "/path/to/src.sss",
"to": "/path/to/dest.css",
"plugins": {
"postcss-plugin": {}
}
}
}
```
### `.postcssrc`
Create a **`.postcssrc`** file in JSON or YAML format.
It's also allowed to use extensions (**`.postcssrc.json`** or **`.postcssrc.yaml`**). That could help your text editor to properly interpret the file.
```
App
| client
| public
|
|- (.postcssrc|.postcssrc.json|.postcssrc.yaml)
|- package.json
```
**`JSON`**
```json
{
"parser": "sugarss",
"map": false,
"from": "/path/to/src.sss",
"to": "/path/to/dest.css",
"plugins": {
"postcss-plugin": {}
}
}
```
**`YAML`**
```yaml
parser: sugarss
map: false
from: "/path/to/src.sss"
to: "/path/to/dest.css"
plugins:
postcss-plugin: {}
```
### `postcss.config.js` or `.postcssrc.js`
You may need some JavaScript logic to generate your config. For this case you can use a file named **`postcss.config.js`** or **`.postcssrc.js`**.
```
App
| client
| public
|
|- (postcss.config.js|.postcssrc.js)
|- package.json
```
You can export the config as an `{Object}`
```js
module.exports = {
parser: 'sugarss',
map: false,
from: '/path/to/src.sss',
to: '/path/to/dest.css',
plugins: {
'postcss-plugin': {}
}
}
```
Or export a `{Function}` that returns the config (more about the param `ctx` below)
```js
module.exports = (ctx) => ({
parser: ctx.parser ? 'sugarss' : false,
map: ctx.env === 'development' ? ctx.map : false,
from: ctx.from,
to: ctx.to,
plugins: {
'postcss-plugin': ctx.plugin
}
})
```
Plugins can be loaded in either using an `{Object}` or an `{Array}`.
##### `{Object}`
```js
module.exports = (ctx) => ({
...options
plugins: {
'postcss-plugin': ctx.plugin
}
})
```
##### `{Array}`
```js
module.exports = (ctx) => ({
...options
plugins: [
require('postcss-plugin')(ctx.plugin)
]
})
```
> :warning: When using an Array, make sure to `require()` them.
<h2 align="center">Options</h2>
**`parser`**:
```js
'parser': 'sugarss'
```
**`syntax`**:
```js
'syntax': 'postcss-scss'
```
**`stringifier`**:
```js
'stringifier': 'midas'
```
[**`map`**:](https://github.com/postcss/postcss/blob/master/docs/source-maps.md)
```js
'map': 'inline'
```
**`from`**:
```js
from: 'path/to/src.css'
```
**`to`**:
```js
to: 'path/to/dest.css'
```
<h2 align="center">Plugins</h2>
### Options
**`{} || null`**: Plugin loads with defaults.
```js
'postcss-plugin': {} || null
```
> :warning: `{}` must be an **empty** object
**`[Object]`**: Plugin loads with given options.
```js
'postcss-plugin': { option: '', option: '' }
```
**`false`**: Plugin will not be loaded.
```js
'postcss-plugin': false
```
### Order
Plugin **order** is determined by declaration in the plugins section.
```js
{
plugins: {
'postcss-plugin': {}, // plugins[0]
'postcss-plugin': {}, // plugins[1]
'postcss-plugin': {} // plugins[2]
}
}
```
<h2 align="center">Context</h2>
When using a function (`postcss.config.js` or `.postcssrc.js`), it is possible to pass context to `postcss-load-config`, which will be evaluated while loading your config. By default `ctx.env (process.env.NODE_ENV)` and `ctx.cwd (process.cwd())` are available.
<h2 align="center">Examples</h2>
**postcss.config.js**
```js
module.exports = (ctx) => ({
parser: ctx.parser ? 'sugarss' : false,
map: ctx.env === 'development' ? ctx.map : false,
plugins: {
'postcss-import': {},
'postcss-nested': {},
cssnano: ctx.env === 'production' ? {} : false
}
})
```
### <img width="80" height="80" src="https://worldvectorlogo.com/logos/nodejs-icon.svg">
```json
"scripts": {
"build": "NODE_ENV=production node postcss",
"start": "NODE_ENV=development node postcss"
}
```
```js
const { readFileSync } = require('fs')
const postcss = require('postcss')
const postcssrc = require('postcss-load-config')
const css = readFileSync('index.sss', 'utf8')
const ctx = { parser: true, map: 'inline' }
postcssrc(ctx).then(({ plugins, options }) => {
postcss(plugins)
.process(css, options)
.then((result) => console.log(result.css))
})
```
### <img width="80" height="80" src="https://worldvectorlogo.com/logos/gulp.svg">
```json
"scripts": {
"build": "NODE_ENV=production gulp",
"start": "NODE_ENV=development gulp"
}
```
```js
const { task, src, dest, series, watch } = require('gulp')
const postcss = require('gulp-postcssrc')
const css = () => {
src('src/*.css')
.pipe(postcss())
.pipe(dest('dest'))
})
task('watch', () => {
watch(['src/*.css', 'postcss.config.js'], css)
})
task('default', series(css, 'watch'))
```
### <img width="80" height="80" src="https://worldvectorlogo.com/logos/webpack.svg">
```json
"scripts": {
"build": "NODE_ENV=production webpack",
"start": "NODE_ENV=development webpack-dev-server"
}
```
```js
module.exports = (env) => ({
module: {
rules: [
{
test: /\.css$/
use: [
'style-loader',
{
loader: 'css-loader',
options: { importLoaders: 1 } }
},
'postcss-loader'
]
}
]
}
})
```
<h2 align="center">Maintainers</h2>
<table>
<tbody>
<tr>
<td align="center">
<img width="150 height="150"
src="https://avatars.githubusercontent.com/u/5419992?v=3&s=150">
<br />
<a href="https://github.com/michael-ciniawsky">Michael Ciniawsky</a>
</td>
<td align="center">
<img width="150 height="150"
src="https://avatars.githubusercontent.com/u/2437969?v=3&s=150">
<br />
<a href="https://github.com/ertrzyiks">Mateusz Derks</a>
</td>
</tr>
<tbody>
</table>
<h2 align="center">Contributors</h2>
<table>
<tbody>
<tr>
<td align="center">
<img width="150" height="150"
src="https://avatars.githubusercontent.com/u/1483538?v=3&s=150">
<br />
<a href="https://github.com/sparty02">Ryan Dunckel</a>
</td>
<td align="center">
<img width="150" height="150"
src="https://avatars.githubusercontent.com/u/6249643?v=3&s=150">
<br />
<a href="https://github.com/pcgilday">Patrick Gilday</a>
</td>
<td align="center">
<img width="150" height="150"
src="https://avatars.githubusercontent.com/u/5603632?v=3&s=150">
<br />
<a href="https://github.com/daltones">Dalton Santos</a>
</td>
</tr>
<tbody>
</table>
[npm]: https://img.shields.io/npm/v/postcss-load-config.svg
[npm-url]: https://npmjs.com/package/postcss-load-config
[node]: https://img.shields.io/node/v/postcss-load-plugins.svg
[node-url]: https://nodejs.org/
[deps]: https://david-dm.org/michael-ciniawsky/postcss-load-config.svg
[deps-url]: https://david-dm.org/michael-ciniawsky/postcss-load-config
[style]: https://img.shields.io/badge/code%20style-standard-yellow.svg
[style-url]: http://standardjs.com/
[tests]: http://img.shields.io/travis/michael-ciniawsky/postcss-load-config.svg
[tests-url]: https://travis-ci.org/michael-ciniawsky/postcss-load-config
[cover]: https://coveralls.io/repos/github/michael-ciniawsky/postcss-load-config/badge.svg
[cover-url]: https://coveralls.io/github/michael-ciniawsky/postcss-load-config
[chat]: https://img.shields.io/gitter/room/postcss/postcss.svg
[chat-url]: https://gitter.im/postcss/postcss

View File

@@ -0,0 +1,69 @@
// ------------------------------------
// # POSTCSS - LOAD CONFIG - INDEX
// ------------------------------------
'use strict'
var resolve = require('path').resolve
var config = require('cosmiconfig')
var assign = require('object-assign')
var loadOptions = require('postcss-load-options/lib/options.js')
var loadPlugins = require('postcss-load-plugins/lib/plugins.js')
/**
* Autoload Config for PostCSS
*
* @author Michael Ciniawsky (@michael-ciniawsky) <michael.ciniawsky@gmail.com>
* @license MIT
*
* @module postcss-load-config
* @version 1.2.0
*
* @requires comsiconfig
* @requires object-assign
* @requires postcss-load-options
* @requires postcss-load-plugins
*
* @method postcssrc
*
* @param {Object} ctx Context
* @param {String} path Config Directory
* @param {Object} options Config Options
*
* @return {Promise} config PostCSS Config
*/
module.exports = function postcssrc (ctx, path, options) {
ctx = assign({ cwd: process.cwd(), env: process.env.NODE_ENV }, ctx)
path = path ? resolve(path) : process.cwd()
options = assign({ rcExtensions: true }, options)
if (!ctx.env) process.env.NODE_ENV = 'development'
var file
return config('postcss', options)
.load(path)
.then(function (result) {
if (!result) throw Error('No PostCSS Config found in: ' + path)
file = result ? result.filepath : ''
return result ? result.config : {}
})
.then(function (config) {
if (typeof config === 'function') config = config(ctx)
else config = assign(config, ctx)
if (!config.plugins) config.plugins = []
return {
plugins: loadPlugins(config),
options: loadOptions(config),
file: file
}
})
}

View File

@@ -0,0 +1,100 @@
{
"_from": "postcss-load-config@^1.1.0",
"_id": "postcss-load-config@1.2.0",
"_inBundle": false,
"_integrity": "sha1-U56a/J3chiASHr+djDZz4M5Q0oo=",
"_location": "/vue-loader/postcss-load-config",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "postcss-load-config@^1.1.0",
"name": "postcss-load-config",
"escapedName": "postcss-load-config",
"rawSpec": "^1.1.0",
"saveSpec": null,
"fetchSpec": "^1.1.0"
},
"_requiredBy": [
"/vue-loader"
],
"_resolved": "https://registry.npmjs.org/postcss-load-config/-/postcss-load-config-1.2.0.tgz",
"_shasum": "539e9afc9ddc8620121ebf9d8c3673e0ce50d28a",
"_spec": "postcss-load-config@^1.1.0",
"_where": "C:\\xampp\\htdocs\\w4rpservices\\node_modules\\vue-loader",
"author": {
"name": "Michael Ciniawky",
"email": "michael.ciniawsky@gmail.com"
},
"bugs": {
"url": "https://github.com/michael-ciniawsky/postcss-load-config/issues"
},
"bundleDependencies": false,
"contributors": [
{
"name": "Mateusz Derks",
"url": "http://ertrzyiks.me"
},
{
"name": "Ryan Dunckel",
"email": "sparty02@gmail.com"
},
{
"name": "Patrick Gilday"
},
{
"name": "Dalton Santos"
}
],
"dependencies": {
"cosmiconfig": "^2.1.0",
"object-assign": "^4.1.0",
"postcss-load-options": "^1.2.0",
"postcss-load-plugins": "^2.3.0"
},
"deprecated": false,
"description": "Autoload Config for PostCSS",
"devDependencies": {
"ava": "^0.18.1",
"coveralls": "^2.11.16",
"cssnano": "^3.10.0",
"jsdoc-to-markdown": "^3.0.0",
"nyc": "^10.1.0",
"postcss": "^5.2.12",
"postcss-cssnext": "^2.8.0",
"postcss-import": "^9.1.0",
"postcss-nested": "^1.0.0",
"postcss-scss": "^0.4.0",
"postcss-sprites": "^4.2.0",
"standard": "^8.6.0",
"standard-changelog": "0.0.1",
"sugarss": "^0.2.0"
},
"engines": {
"node": ">=0.12"
},
"files": [
"index.js"
],
"homepage": "https://github.com/michael-ciniawsky/postcss-load-config#readme",
"keywords": [
"postcss",
"postcss-config"
],
"license": "MIT",
"main": "index.js",
"name": "postcss-load-config",
"repository": {
"type": "git",
"url": "git+https://github.com/michael-ciniawsky/postcss-load-config.git"
},
"scripts": {
"clean": "rm -rf .nyc_output coverage jsdoc-api dmd",
"docs": "jsdoc2md index.js > INDEX.md",
"lint": "standard",
"logs": "standard-changelog -i CHANGELOG.md -w",
"start": "sudo npm run clean && npm run lint && sudo npm test",
"test": "nyc ava -v test/err/index.js test/pkg/index.js test/rc/index.js test/js/**/index.js"
},
"version": "1.2.0"
}

View File

@@ -0,0 +1,30 @@
'use strict';
var Module = require('module');
var path = require('path');
module.exports = function requireFromString(code, filename, opts) {
if (typeof filename === 'object') {
opts = filename;
filename = undefined;
}
opts = opts || {};
filename = filename || '';
opts.appendPaths = opts.appendPaths || [];
opts.prependPaths = opts.prependPaths || [];
if (typeof code !== 'string') {
throw new Error('code must be a string, not ' + typeof code);
}
var paths = Module._nodeModulePaths(path.dirname(filename));
var m = new Module(filename, module.parent);
m.filename = filename;
m.paths = [].concat(opts.prependPaths).concat(paths).concat(opts.appendPaths);
m._compile(code, filename);
return m.exports;
};

View File

@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) Vsevolod Strukchinsky <floatdrop@gmail.com> (github.com/floatdrop)
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

View File

@@ -0,0 +1,58 @@
{
"_from": "require-from-string@^1.1.0",
"_id": "require-from-string@1.2.1",
"_inBundle": false,
"_integrity": "sha1-UpyczvJzgK3+yaL5ZbZJu+5jZBg=",
"_location": "/vue-loader/require-from-string",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "require-from-string@^1.1.0",
"name": "require-from-string",
"escapedName": "require-from-string",
"rawSpec": "^1.1.0",
"saveSpec": null,
"fetchSpec": "^1.1.0"
},
"_requiredBy": [
"/vue-loader/cosmiconfig"
],
"_resolved": "https://registry.npmjs.org/require-from-string/-/require-from-string-1.2.1.tgz",
"_shasum": "529c9ccef27380adfec9a2f965b649bbee636418",
"_spec": "require-from-string@^1.1.0",
"_where": "C:\\xampp\\htdocs\\w4rpservices\\node_modules\\vue-loader\\node_modules\\cosmiconfig",
"author": {
"name": "Vsevolod Strukchinsky",
"email": "floatdrop@gmail.com",
"url": "github.com/floatdrop"
},
"bugs": {
"url": "https://github.com/floatdrop/require-from-string/issues"
},
"bundleDependencies": false,
"dependencies": {},
"deprecated": false,
"description": "Require module from string",
"devDependencies": {
"mocha": "*"
},
"engines": {
"node": ">=0.10.0"
},
"files": [
"index.js"
],
"homepage": "https://github.com/floatdrop/require-from-string#readme",
"keywords": [],
"license": "MIT",
"name": "require-from-string",
"repository": {
"type": "git",
"url": "git+https://github.com/floatdrop/require-from-string.git"
},
"scripts": {
"test": "mocha"
},
"version": "1.2.1"
}

View File

@@ -0,0 +1,56 @@
# require-from-string [![Build Status](https://travis-ci.org/floatdrop/require-from-string.svg?branch=master)](https://travis-ci.org/floatdrop/require-from-string)
Load module from string in Node.
## Install
```
$ npm install --save require-from-string
```
## Usage
```js
var requireFromString = require('require-from-string');
requireFromString('module.exports = 1');
//=> 1
```
## API
### requireFromString(code, [filename], [options])
#### code
*Required*
Type: `string`
Module code.
#### filename
Type: `string`
Default: `''`
Optional filename.
#### options
Type: `object`
##### appendPaths
Type: `Array`
List of `paths`, that will be appended to module `paths`. Useful, when you want
to be able require modules from these paths.
##### prependPaths
Type: `Array`
Same as `appendPath`, but paths will be prepended.
## License
MIT © [Vsevolod Strukchinsky](http://github.com/floatdrop)

137
node_modules/vue-loader/package.json generated vendored Normal file
View File

@@ -0,0 +1,137 @@
{
"_from": "vue-loader@^13.7.1",
"_id": "vue-loader@13.7.3",
"_inBundle": false,
"_integrity": "sha512-ACCwbfeC6HjY2pnDii+Zer+MZ6sdOtwvLmDXRK/BoD3WNR551V22R6KEagwHoTRJ0ZlIhpCBkptpCU6+Ri/05w==",
"_location": "/vue-loader",
"_phantomChildren": {
"is-directory": "0.3.1",
"js-yaml": "3.7.0",
"object-assign": "4.1.1",
"os-homedir": "1.0.2",
"parse-json": "2.2.0",
"postcss-load-options": "1.2.0",
"postcss-load-plugins": "2.3.0"
},
"_requested": {
"type": "range",
"registry": true,
"raw": "vue-loader@^13.7.1",
"name": "vue-loader",
"escapedName": "vue-loader",
"rawSpec": "^13.7.1",
"saveSpec": null,
"fetchSpec": "^13.7.1"
},
"_requiredBy": [
"/laravel-mix"
],
"_resolved": "https://registry.npmjs.org/vue-loader/-/vue-loader-13.7.3.tgz",
"_shasum": "e07440f78230a639d00ada4da7b96d0e9d62037f",
"_spec": "vue-loader@^13.7.1",
"_where": "C:\\xampp\\htdocs\\w4rpservices\\node_modules\\laravel-mix",
"author": {
"name": "Evan You"
},
"bugs": {
"url": "https://github.com/vuejs/vue-loader/issues"
},
"bundleDependencies": false,
"dependencies": {
"consolidate": "^0.14.0",
"hash-sum": "^1.0.2",
"loader-utils": "^1.1.0",
"lru-cache": "^4.1.1",
"postcss": "^6.0.8",
"postcss-load-config": "^1.1.0",
"postcss-selector-parser": "^2.0.0",
"prettier": "^1.7.0",
"resolve": "^1.4.0",
"source-map": "^0.6.1",
"vue-hot-reload-api": "^2.2.0",
"vue-style-loader": "^3.0.0",
"vue-template-es2015-compiler": "^1.6.0"
},
"deprecated": false,
"description": "Vue single-file component loader for Webpack",
"devDependencies": {
"babel-core": "^6.25.0",
"babel-loader": "^7.0.0",
"babel-preset-env": "^1.6.0",
"chai": "^4.1.0",
"coffee-loader": "^0.7.2",
"coffee-script": "^1.12.7",
"css-loader": "^0.28.4",
"eslint": "^3.19.0",
"eslint-plugin-vue-libs": "^1.2.0",
"expose-loader": "^0.7.1",
"extract-text-webpack-plugin": "^3.0.0",
"file-loader": "^1.1.5",
"gitbook-plugin-edit-link": "^2.0.2",
"gitbook-plugin-github": "^3.0.0",
"gitbook-plugin-theme-vuejs": "^1.1.0",
"husky": "^0.14.3",
"inject-loader": "^3.0.1",
"js-yaml": "^3.9.1",
"jsdom": "^9.2.1",
"lint-staged": "^4.0.2",
"marked": "^0.3.6",
"memory-fs": "^0.4.1",
"mkdirp": "^0.5.1",
"mocha": "^4.0.1",
"node-libs-browser": "^2.0.0",
"normalize-newline": "^3.0.0",
"null-loader": "^0.1.1",
"pug": "^2.0.0-rc.2",
"raw-loader": "^0.5.1",
"skeleton-loader": "1.1.3",
"stylus": "^0.54.5",
"stylus-loader": "^3.0.1",
"sugarss": "^1.0.0",
"url-loader": "^0.6.2",
"vue": "^2.5.0",
"vue-server-renderer": "^2.5.0",
"vue-template-compiler": "^2.5.0",
"webpack": "^3.7.1"
},
"files": [
"index.js",
"lib"
],
"homepage": "https://github.com/vuejs/vue-loader",
"keywords": [
"vue",
"webpack",
"loader"
],
"license": "MIT",
"lint-staged": {
"lib/**/*.js": [
"eslint --fix",
"git add"
],
"test/**/*.js": [
"eslint --fix",
"git add"
]
},
"main": "index.js",
"name": "vue-loader",
"peerDependencies": {
"css-loader": "*",
"vue-template-compiler": "^2.0.0"
},
"repository": {
"type": "git",
"url": "git+https://github.com/vuejs/vue-loader.git"
},
"scripts": {
"docs": "cd docs && gitbook install && gitbook serve",
"docs:deploy": "bash ./docs/deploy.sh",
"lint": "eslint lib test",
"lint:fix": "eslint lib test --fix",
"precommit": "lint-staged",
"test": "eslint lib && mocha --slow 5000 --timeout 10000"
},
"version": "13.7.3"
}