Skip to content

Commit

Permalink
style: format code
Browse files Browse the repository at this point in the history
  • Loading branch information
SASUKE40 committed Apr 13, 2020
1 parent 2c4a6c2 commit 92b2744
Show file tree
Hide file tree
Showing 8 changed files with 80 additions and 67 deletions.
52 changes: 28 additions & 24 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ export default (options = {}) => {
const postcssPlugins = Array.isArray(options.plugins) ?
options.plugins.filter(Boolean) :
options.plugins
const sourceMap = options.sourceMap
const { sourceMap } = options
const postcssLoaderOptions = {
/** Inject CSS as `<style>` to `<head>` */
inject: typeof options.inject === 'function' ? options.inject : inferOption(options.inject, {}),
Expand Down Expand Up @@ -56,6 +56,7 @@ export default (options = {}) => {
['less', options.use.less || {}]
]
}

use.unshift(['postcss', postcssLoaderOptions])

const loaders = new Loaders({
Expand Down Expand Up @@ -86,7 +87,7 @@ export default (options = {}) => {
plugin: this
}

const res = await loaders.process(
const result = await loaders.process(
{
code,
map: undefined
Expand All @@ -99,40 +100,40 @@ export default (options = {}) => {
}

if (postcssLoaderOptions.extract) {
extracted.set(id, res.extracted)
extracted.set(id, result.extracted)
return {
code: res.code,
code: result.code,
map: { mappings: '' }
}
}

return {
code: res.code,
map: res.map || { mappings: '' }
code: result.code,
map: result.map || { mappings: '' }
}
},

augmentChunkHash() {
if (extracted.size === 0) return
const extractedValue = Array.from(extracted).reduce((obj, [key, value]) => ({
...obj,
const extractedValue = [...extracted].reduce((object, [key, value]) => ({
...object,
[key]: value
}), {})
return JSON.stringify(extractedValue)
},

async generateBundle(opts, bundle) {
async generateBundle(options_, bundle) {
if (
extracted.size === 0 ||
!(opts.dir || opts.file)
!(options_.dir || options_.file)
) return

// TODO: support `[hash]`
const dir = opts.dir || path.dirname(opts.file)
const dir = options_.dir || path.dirname(options_.file)
const file =
opts.file ||
options_.file ||
path.join(
opts.dir,
options_.dir,
Object.keys(bundle).find(fileName => bundle[fileName].isEntry)
)
const getExtracted = () => {
Expand All @@ -141,7 +142,7 @@ export default (options = {}) => {
normalizePath(path.relative(dir, postcssLoaderOptions.extract)) :
`${path.basename(file, path.extname(file))}.css`
const concat = new Concat(true, fileName, '\n')
const entries = Array.from(extracted.values())
const entries = [...extracted.values()]
const { modules } = bundle[normalizePath(path.relative(dir, file))]

if (modules) {
Expand All @@ -150,14 +151,17 @@ export default (options = {}) => {
(a, b) => fileList.indexOf(a.id) - fileList.indexOf(b.id)
)
}
for (const res of entries) {
const relative = normalizePath(path.relative(dir, res.id))
const map = res.map || null

for (const result of entries) {
const relative = normalizePath(path.relative(dir, result.id))
const map = result.map || null
if (map) {
map.file = fileName
}
concat.add(relative, res.code, map)

concat.add(relative, result.code, map)
}

let code = concat.content

if (sourceMap === 'inline') {
Expand Down Expand Up @@ -187,16 +191,16 @@ export default (options = {}) => {
let { code, codeFileName, map, mapFileName } = getExtracted()
// Perform cssnano on the extracted file
if (postcssLoaderOptions.minimize) {
const cssOpts = postcssLoaderOptions.minimize
cssOpts.from = codeFileName
const cssOptions = postcssLoaderOptions.minimize
cssOptions.from = codeFileName
if (sourceMap === 'inline') {
cssOpts.map = { inline: true }
cssOptions.map = { inline: true }
} else if (sourceMap === true && map) {
cssOpts.map = { prev: map }
cssOpts.to = codeFileName
cssOptions.map = { prev: map }
cssOptions.to = codeFileName
}

const result = await require('cssnano').process(code, cssOpts)
const result = await require('cssnano').process(code, cssOptions)
code = result.css

if (sourceMap === true && result.map && result.map.toString) {
Expand Down
2 changes: 1 addition & 1 deletion src/less-loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ export default {
async process({ code }) {
const less = loadModule('less')
if (!less) {
throw new Error(`You need to install "less" packages in order to process Less files`)
throw new Error('You need to install "less" packages in order to process Less files')
}

let { css, map, imports } = await pify(less.render.bind(less))(code, {
Expand Down
15 changes: 9 additions & 6 deletions src/loaders.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ const matchFile = (filepath, condition) => {
if (typeof condition === 'function') {
return condition(filepath)
}

return condition && condition.test(filepath)
}

Expand All @@ -18,9 +19,11 @@ export default class Loaders {
if (typeof rule === 'string') {
return [rule]
}

if (Array.isArray(rule)) {
return rule
}

throw new TypeError('The rule in `use` option must be string or Array!')
})
this.loaders = []
Expand All @@ -44,6 +47,7 @@ export default class Loaders {
if (existing) {
this.removeLoader(loader.name)
}

this.loaders.push(loader)
return this
}
Expand Down Expand Up @@ -77,12 +81,10 @@ export default class Loaders {
.reverse()
.map(([name, options]) => {
const loader = this.getLoader(name)
const loaderContext = Object.assign(
{
options: options || {}
},
context
)
const loaderContext = {
options: options || {},
...context
}

return v => {
if (
Expand All @@ -91,6 +93,7 @@ export default class Loaders {
) {
return loader.process.call(loaderContext, v)
}

// Otherwise directly return input value
return v
}
Expand Down
50 changes: 27 additions & 23 deletions src/postcss-loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,15 @@ const styleInjectPath = require

function loadConfig(id, { ctx: configOptions, path: configPath }) {
const handleError = err => {
if (err.message.indexOf('No PostCSS Config found') === -1) {
if (!err.message.includes('No PostCSS Config found')) {
throw err
}

// Return empty options for PostCSS
return {}
}

configPath = configPath ? path.resolve(configPath) : path.dirname(id)
configPath = configPath ? path.resultolve(configPath) : path.dirname(id)

This comment has been minimized.

Copy link
@nstepien

nstepien Apr 13, 2020

Contributor

Typo?

This comment has been minimized.

Copy link
@SASUKE40

SASUKE40 Apr 14, 2020

Author Collaborator

Yep, thanks for reviewing.

This comment has been minimized.

Copy link
@SASUKE40

SASUKE40 Apr 14, 2020

Author Collaborator

It has been fixed in version 2.6.2.

const ctx = {
file: {
extname: path.extname(id),
Expand All @@ -32,8 +33,8 @@ function loadConfig(id, { ctx: configOptions, path: configPath }) {
return findPostcssConfig(ctx, configPath).catch(handleError)
}

function escapeClassNameDashes(str) {
return str.replace(/-+/g, match => {
function escapeClassNameDashes(string) {
return string.replace(/-+/g, match => {
return `$${match.replace(/-/g, '_')}$`
})
}
Expand All @@ -60,7 +61,7 @@ export default {
await loadConfig(this.id, this.options.config) :
{}

const options = this.options
const { options } = this
const plugins = [
...(options.postcss.plugins || []),
...(config.plugins || [])
Expand Down Expand Up @@ -98,27 +99,27 @@ export default {
plugins.push(require('cssnano')(options.minimize))
}

const postcssOpts = {
const postcssOptions = {
...this.options.postcss,
...config.options,
// Allow overriding `to` for some plugins that are relying on this value
to: options.to || this.id,
// Followings are never modified by user config config
from: this.id,
map: this.sourceMap ?
shouldExtract ?
(shouldExtract ?
{ inline: false, annotation: false } :
{ inline: true, annotation: false } :
{ inline: true, annotation: false }) :
false
}
delete postcssOpts.plugins
delete postcssOptions.plugins

postcssOpts.parser = ensurePostCSSOption(postcssOpts.parser)
postcssOpts.syntax = ensurePostCSSOption(postcssOpts.syntax)
postcssOpts.stringifier = ensurePostCSSOption(postcssOpts.stringifier)
postcssOptions.parser = ensurePostCSSOption(postcssOptions.parser)
postcssOptions.syntax = ensurePostCSSOption(postcssOptions.syntax)
postcssOptions.stringifier = ensurePostCSSOption(postcssOptions.stringifier)

if (map && postcssOpts.map) {
postcssOpts.map.prev = typeof map === 'string' ? JSON.parse(map) : map
if (map && postcssOptions.map) {
postcssOptions.map.prev = typeof map === 'string' ? JSON.parse(map) : map
}

if (plugins.length === 0) {
Expand All @@ -130,19 +131,19 @@ export default {
plugins.push(noopPlugin())
}

const res = await postcss(plugins).process(code, postcssOpts)
const result = await postcss(plugins).process(code, postcssOptions)

for (const msg of res.messages) {
if (msg.type === 'dependency') {
this.dependencies.add(msg.file)
for (const message of result.messages) {
if (message.type === 'dependency') {
this.dependencies.add(message.file)
}
}

for (const warning of res.warnings()) {
for (const warning of result.warnings()) {
this.warn(warning)
}

const outputMap = res.map && JSON.parse(res.map.toString())
const outputMap = result.map && JSON.parse(result.map.toString())
if (outputMap && outputMap.sources) {
outputMap.sources = outputMap.sources.map(v => normalizePath(v))
}
Expand All @@ -167,9 +168,11 @@ export default {
`Exported "${name}" as "${newName}" in ${humanlizePath(this.id)}`
)
}

if (!json[newName]) {
json[newName] = json[name]
}

output += `export var ${newName} = ${JSON.stringify(json[name])};\n`
}
}
Expand All @@ -179,18 +182,19 @@ export default {
output += `export default ${JSON.stringify(modulesExported[this.id])};`
extracted = {
id: this.id,
code: res.css,
code: result.css,
map: outputMap
}
} else {
const module = supportModules ?
JSON.stringify(modulesExported[this.id]) :
cssVariableName
output +=
`var ${cssVariableName} = ${JSON.stringify(res.css)};\n` +
`var ${cssVariableName} = ${JSON.stringify(result.css)};\n` +
`export default ${module};\n` +
`export const stylesheet=${JSON.stringify(res.css)};`
`export const stylesheet=${JSON.stringify(result.css)};`
}

if (!shouldExtract && shouldInject) {
if (typeof options.inject === 'function') {
output += options.inject(cssVariableName, this.id)
Expand Down
21 changes: 11 additions & 10 deletions src/sass-loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ import { loadModule } from './utils/load-module'
const threadPoolSize = process.env.UV_THREADPOOL_SIZE || 4
const workQueue = new PQueue({ concurrency: threadPoolSize - 1 })

const moduleRe = /^~([a-z0-9]|@).+/i
const moduleRe = /^~([a-z\d]|@).+/i

const getUrlOfPartial = url => {
const parsedUrl = path.parse(url)
Expand Down Expand Up @@ -62,10 +62,10 @@ export default {
// Give precedence to importing a partial
resolvePromise(partialUrl, options)
.then(finishImport)
.catch(err => {
.catch(error => {
if (
err.code === 'MODULE_NOT_FOUND' ||
err.code === 'ENOENT'
error.code === 'MODULE_NOT_FOUND' ||
error.code === 'ENOENT'
) {
resolvePromise(moduleUrl, options)
.then(finishImport)
Expand All @@ -77,13 +77,14 @@ export default {
}
].concat(this.options.importer || [])
})
.then(res => {
for (const file of res.stats.includedFiles) {
.then(result => {
for (const file of result.stats.includedFiles) {
this.dependencies.add(file)
}

resolve({
code: res.css.toString(),
map: res.map && res.map.toString()
code: result.css.toString(),
map: result.map && result.map.toString()
})
})
.catch(reject)
Expand All @@ -103,8 +104,8 @@ function loadSassOrThrow() {

// Throwing exception if module can't be loaded
throw new Error(
`You need to install one of the following packages: ` +
'You need to install one of the following packages: ' +
sassModuleIds.map(moduleId => `"${moduleId}"`).join(', ') + ' ' +
`in order to process SASS files`
'in order to process SASS files'
)
}
2 changes: 1 addition & 1 deletion src/stylus-loader.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export default {
async process({ code }) {
const stylus = loadModule('stylus')
if (!stylus) {
throw new Error(`You need to install "stylus" packages in order to process Stylus files`)
throw new Error('You need to install "stylus" packages in order to process Stylus files')
}

const style = stylus(code, {
Expand Down
2 changes: 1 addition & 1 deletion src/utils/humanlize-path.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@ import path from 'path'
import normalizePath from './normalize-path'

const humanlizePath = filepath => normalizePath(path.relative(process.cwd(),
filepath))
filepath))

export default humanlizePath
Loading

0 comments on commit 92b2744

Please sign in to comment.