-
Notifications
You must be signed in to change notification settings - Fork 17
/
loader.js
75 lines (64 loc) · 1.81 KB
/
loader.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
// Usage: `require('carmi/loader!./file.carmi')`
// or just setup as a default loader for `.carmi.js$` files
'use strict'
const execa = require('execa')
const dargs = require('dargs')
const tempy = require('tempy')
const fs = require('fs-extra')
const loaderUtils = require('loader-utils')
const getCacheFilePath = require('./src/get-cache-file-path')
const queue = []
async function addToQueue() {
const item = {promise: null, resolve: null}
queue.push(item)
item.promise = new Promise((resolve) => {
item.resolve = resolve
})
if (queue.length > 1) {
await queue[queue.length - 2].promise
}
}
function finish() {
const item = queue.shift()
item.resolve()
}
async function CarmiLoader(loader) {
const callback = loader.async()
const tempOutputPath = tempy.file({extension: 'js'})
const loaderOptions = loaderUtils.getOptions(loader) || {}
const options = {
source: loader.getDependencies()[0],
format: 'cjs',
output: tempOutputPath,
debug: process.env.NODE_ENV !== 'production',
...loaderOptions
}
options.stats = getCacheFilePath({
fileType: 'stats',
path: options.source,
debug: options.debug,
format: options.format,
name: 'model'
});
await addToQueue()
let compiled
let err = null
try {
await execa('node', [require.resolve('./bin/carmi'), ...dargs(options, {ignoreFalse: true})])
compiled = fs.readFileSync(tempOutputPath, 'utf8')
if (fs.pathExistsSync(options.stats)) {
fs.readJSONSync(options.stats).forEach((filePath) => {
// Add those modules as loader dependencies
// See https://webpack.js.org/contribute/writing-a-loader/#loader-dependencies
loader.addDependency(filePath)
})
}
} catch (e) {
err = e || new Error(`Error compiling ${options.source}`)
}
finish()
callback(err, compiled)
}
module.exports = function CarmiLoaderPublic() {
CarmiLoader(this)
}