forked from callstack/linaria
/
index.ts
152 lines (128 loc) · 4.33 KB
/
index.ts
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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
/**
* This file contains a Webpack loader for Linaria.
* It uses the transform.ts function to generate class names from source code,
* returns transformed code without template literals and attaches generated source maps
*/
import fs from 'fs';
import path from 'path';
import loaderUtils from 'loader-utils';
import mkdirp from 'mkdirp';
import normalize from 'normalize-path';
import enhancedResolve from 'enhanced-resolve';
import findYarnWorkspaceRoot from 'find-yarn-workspace-root';
import type { RawSourceMap } from 'source-map';
import cosmiconfig from 'cosmiconfig';
import { EvalCache, Module, transform } from '@linaria/babel-preset';
import { debug } from '@linaria/logger';
const workspaceRoot = findYarnWorkspaceRoot();
const lernaConfig = cosmiconfig('lerna', {
searchPlaces: ['lerna.json'],
}).searchSync();
const lernaRoot =
lernaConfig !== null ? path.dirname(lernaConfig.filepath) : null;
export default function webpack5Loader(
this: any,
content: string,
inputSourceMap: RawSourceMap | null
) {
debug('loader', this.resourcePath);
EvalCache.clearForFile(this.resourcePath);
const {
sourceMap = undefined,
cacheDirectory = '.linaria-cache',
preprocessor = undefined,
extension = '.linaria.css',
resolveOptions = {},
...rest
} = this.getOptions() || {};
const root = workspaceRoot || lernaRoot || process.cwd();
const baseOutputFileName = this.resourcePath.replace(/\.[^.]+$/, extension);
const outputFilename = normalize(
path.join(
path.isAbsolute(cacheDirectory)
? cacheDirectory
: path.join(process.cwd(), cacheDirectory),
this.resourcePath.includes(root)
? path.relative(root, baseOutputFileName)
: baseOutputFileName
)
);
const resolveSync = enhancedResolve.create.sync(
// this._compilation is a deprecated API
// However there seems to be no other way to access webpack's resolver
// There is this.resolve, but it's asynchronous
// Another option is to read the webpack.config.js, but it won't work for programmatic usage
// This API is used by many loaders/plugins, so hope we're safe for a while
{
...(this._compilation?.options.resolve ?? {}),
...resolveOptions,
}
);
let result;
const originalResolveFilename = Module._resolveFilename;
try {
// Use webpack's resolution when evaluating modules
Module._resolveFilename = (id, { filename }) => {
const result = resolveSync(path.dirname(filename), id);
if (!result) {
// enhanced-resolve v4 throws a error when dependency is missed
throw new Error('No result');
}
this.addDependency(result);
return result;
};
result = transform(content, {
filename: path.relative(process.cwd(), this.resourcePath),
inputSourceMap: inputSourceMap ?? undefined,
outputFilename,
pluginOptions: rest,
preprocessor,
});
} finally {
// Restore original behaviour
Module._resolveFilename = originalResolveFilename;
}
if (result.cssText) {
let { cssText } = result;
if (sourceMap) {
cssText += `/*# sourceMappingURL=data:application/json;base64,${Buffer.from(
result.cssSourceMapText || ''
).toString('base64')}*/`;
}
if (result.dependencies?.length) {
result.dependencies.forEach((dep) => {
try {
const f = resolveSync(path.dirname(this.resourcePath), dep);
this.addDependency(f);
} catch (e) {
// eslint-disable-next-line no-console
console.warn(`[linaria] failed to add dependency for: ${dep}`, e);
}
});
}
// Read the file first to compare the content
// Write the new content only if it's changed
// This will prevent unnecessary WDS reloads
let currentCssText;
try {
currentCssText = fs.readFileSync(outputFilename, 'utf-8');
} catch (e) {
// Ignore error
}
if (currentCssText !== cssText) {
mkdirp.sync(path.dirname(outputFilename));
fs.writeFileSync(outputFilename, cssText);
}
this.callback(
null,
`${result.code}\n\nrequire(${loaderUtils.stringifyRequest(
this,
outputFilename
)});`,
result.sourceMap ?? undefined
);
return;
}
this.callback(null, result.code, result.sourceMap ?? undefined);
}
export type Webpack5Loader = typeof webpack5Loader;