Skip to content

Commit 993f3c1

Browse files
committed
add prefix loader
1 parent 81056c0 commit 993f3c1

File tree

2 files changed

+49
-0
lines changed

2 files changed

+49
-0
lines changed

packages/nextjs/rollup.npm.config.js

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -29,4 +29,19 @@ export default [
2929
},
3030
}),
3131
),
32+
...makeNPMConfigVariants(
33+
makeBaseNPMConfig({
34+
entrypoints: ['src/config/prefixLoader.ts'],
35+
36+
packageSpecificConfig: {
37+
output: {
38+
// make it so Rollup calms down about the fact that we're doing `export { loader as default }`
39+
exports: 'default',
40+
41+
// preserve the original file structure (i.e., so that everything is still relative to `src`)
42+
entryFileNames: 'config/[name].js',
43+
},
44+
},
45+
}),
46+
),
3247
];
Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
import * as fs from 'fs';
2+
import * as path from 'path';
3+
4+
type LoaderOptions = {
5+
distDir: string;
6+
};
7+
// TODO Use real webpack types
8+
type LoaderThis = {
9+
// Webpack 4
10+
query?: LoaderOptions;
11+
// Webpack 5
12+
getOptions?: () => LoaderOptions;
13+
addDependency: (filepath: string) => void;
14+
};
15+
16+
/**
17+
* Inject templated code into the beginning of a module.
18+
*/
19+
function prefixLoader(this: LoaderThis, userCode: string): string {
20+
// We know one or the other will be defined, depending on the version of webpack being used
21+
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
22+
const { distDir } = this.getOptions ? this.getOptions() : this.query!;
23+
24+
const templatePath = path.resolve(__dirname, 'prefixLoaderTemplate.js');
25+
this.addDependency(templatePath);
26+
27+
// Fill in the placeholder
28+
let templateCode = fs.readFileSync(templatePath).toString();
29+
templateCode = templateCode.replace('__DIST_DIR__', distDir);
30+
31+
return `${templateCode}\n${userCode}`;
32+
}
33+
34+
export { prefixLoader as default };

0 commit comments

Comments
 (0)