Skip to content

Build sytem: allow customization of some build options (such as global name) to NPM consumers #13685

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 11 commits into from
Jul 28, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
33 changes: 32 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ Prebid.js is open source software that is offered for free as a convenience. Whi
## Usage (as a npm dependency)

**Note**: versions prior to v10 required some Babel plugins to be configured when used as an NPM dependency -
refer to [v9 README](https://github.com/prebid/Prebid.js/blob/9.43.0/README.md).
refer to [v9 README](https://github.com/prebid/Prebid.js/blob/9.43.0/README.md). See also [customize build options](#customize-options)

```javascript
import pbjs from 'prebid.js';
Expand Down Expand Up @@ -56,6 +56,37 @@ declare global {
}
```

<a id="customize-options"></a>

### Customize build options

If you're using Webpack, you can use the `prebid.js/customize/webpackLoader` loader to set the following options:

| Name | Type | Description | Default |
| ---- | ---- | ----------- | ------- |
| globalVarName | String | Prebid global variable name | `"pbjs"` |
| defineGlobal | Boolean | If false, do not set a global variable | `true` |
| distUrlBase | String | Base URL to use for dynamically loaded modules (e.g. debugging-standalone.js) | `"https://cdn.jsdelivr.net/npm/prebid.js/dist/chunks/"` |

For example, to set a custom global variable name:

```javascript
// webpack.conf.js
module.exports = {
module: {
rules: [
{
loader: 'prebid.js/customize/webpackLoader',
options: {
globalVarName: 'myCustomGlobal'
}
},
]
}
}
```


<a name="Install"></a>

## Install
Expand Down
49 changes: 49 additions & 0 deletions customize/buildOptions.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
import path from 'path'
import validate from 'schema-utils'

const boModule = path.resolve(import.meta.dirname, '../dist/src/buildOptions.mjs')

export function getBuildOptionsModule () {
return boModule
}

const schema = {
type: 'object',
properties: {
globalVarName: {
type: 'string',
description: 'Prebid global variable name. Default is "pbjs"',
},
defineGlobal: {
type: 'boolean',
description: 'If false, do not set a global variable. Default is true.'
},
distUrlBase: {
type: 'string',
description: 'Base URL to use for dynamically loaded modules (e.g. debugging-standalone.js)'
}
}
}

export function getBuildOptions (options = {}) {
validate(schema, options, {
name: 'Prebid build options',
})
const overrides = {}
if (options.globalVarName != null) {
overrides.pbGlobal = options.globalVarName
}
['defineGlobal', 'distUrlBase'].forEach((option) => {
if (options[option] != null) {
overrides[option] = options[option]
}
})
return import(getBuildOptionsModule())
.then(({ default: defaultOptions }) => {
return Object.assign(
{},
defaultOptions,
overrides
)
})
}
8 changes: 8 additions & 0 deletions customize/webpackLoader.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
import { getBuildOptions, getBuildOptionsModule } from './buildOptions.mjs'

export default async function (source) {
if (this.resourcePath !== getBuildOptionsModule()) {
return source
}
return `export default ${JSON.stringify(await getBuildOptions(this.getOptions()), null, 2)};`
}
3 changes: 2 additions & 1 deletion eslint.config.js
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@ module.exports = [
// do not lint build-related stuff
'*.js',
'metadata/**/*',
'customize/**/*',
...jsPattern('plugins'),
...jsPattern('.github'),
],
Expand Down Expand Up @@ -99,7 +100,7 @@ module.exports = [
'comma-dangle': 'off',
semi: 'off',
'no-undef': 2,
'no-console': 'error',
'no-console': 'error',
'space-before-function-paren': 'off',
'import/extensions': ['error', 'ignorePackages'],
'no-restricted-syntax': [
Expand Down
32 changes: 25 additions & 7 deletions gulp.precompilation.js
Original file line number Diff line number Diff line change
Expand Up @@ -15,17 +15,21 @@ const {buildOptions} = require('./plugins/buildOptions.js');
// do not generate more than one task for a given build config - so that `gulp.lastRun` can work properly
const PRECOMP_TASKS = new Map();

function babelPrecomp({distUrlBase = null, disableFeatures = null, dev = false} = {}) {
function getDefaults({distUrlBase = null, disableFeatures = null, dev = false}) {
if (dev && distUrlBase == null) {
distUrlBase = argv.distUrlBase || '/build/dev/'
}
return {
disableFeatures: disableFeatures ?? helpers.getDisabledFeatures(),
distUrlBase: distUrlBase ?? argv.distUrlBase,
ES5: argv.ES5
}
}

function babelPrecomp({distUrlBase = null, disableFeatures = null, dev = false} = {}) {
const key = `${distUrlBase}::${disableFeatures}`;
if (!PRECOMP_TASKS.has(key)) {
const babelConfig = require('./babelConfig.js')({
disableFeatures: disableFeatures ?? helpers.getDisabledFeatures(),
prebidDistUrlBase: distUrlBase ?? argv.distUrlBase,
ES5: argv.ES5
});
const babelConfig = require('./babelConfig.js')(getDefaults({distUrlBase, disableFeatures, dev}));
const precompile = function () {
// `since: gulp.lastRun(task)` selects files that have been modified since the last time this gulp process ran `task`
return gulp.src(helpers.getSourcePatterns(), {base: '.', since: gulp.lastRun(precompile)})
Expand Down Expand Up @@ -173,9 +177,23 @@ function generateGlobalDef(options) {
}
}

function generateBuildOptions(options = {}) {
return function (done) {
options = buildOptions(getDefaults(options));
import('./customize/buildOptions.mjs').then(({getBuildOptionsModule}) => {
const dest = getBuildOptionsModule();
if (!fs.existsSync(path.dirname(dest))) {
fs.mkdirSync(path.dirname(dest), {recursive: true});
}
fs.writeFile(dest, `export default ${JSON.stringify(options, null, 2)}`, done);
})
}

}

function precompile(options = {}) {
return gulp.series([
gulp.parallel(['ts', generateMetadataModules]),
gulp.parallel(['ts', generateMetadataModules, generateBuildOptions(options)]),
gulp.parallel([copyVerbatim, babelPrecomp(options)]),
gulp.parallel([publicModules, generateCoreSummary, generateModuleSummary, generateGlobalDef(options)])
]);
Expand Down
4 changes: 3 additions & 1 deletion libraries/riseUtils/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import {BANNER, NATIVE, VIDEO} from '../../src/mediaTypes.js';
import {config} from '../../src/config.js';
import {ADAPTER_VERSION, DEFAULT_CURRENCY, DEFAULT_TTL, SUPPORTED_AD_TYPES} from './constants.js';

import {getGlobalVarName} from '../../src/buildOptions.js';

export const makeBaseSpec = (baseUrl, modes) => {
return {
version: ADAPTER_VERSION,
Expand Down Expand Up @@ -367,7 +369,7 @@ export function generateGeneralParams(generalObject, bidderRequest, adapterVersi

const generalParams = {
wrapper_type: 'prebidjs',
wrapper_vendor: '$$PREBID_GLOBAL$$',
wrapper_vendor: getGlobalVarName(),
wrapper_version: '$prebid.version$',
adapter_version: adapVer,
auction_start: bidderRequest.auctionStart,
Expand Down
4 changes: 3 additions & 1 deletion modules/adagioRtdProvider.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ import { _ADAGIO, getBestWindowForAdagio } from '../libraries/adagioUtils/adagio
import { getGptSlotInfoForAdUnitCode } from '../libraries/gptUtils/gptUtils.js';
import { getBoundingClientRect } from '../libraries/boundingClientRect/boundingClientRect.js';

import {getGlobalVarName} from '../src/buildOptions.js';
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

how is this different than

import {getGlobal} from '../src/prebidGlobal.js';

Copy link
Collaborator Author

@dgirardi dgirardi Jul 28, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

getGlobal returns the global object (the one that has .requestBids() etc); getGlobalVarName returns the global name (e.g. 'pbjs').


/**
* @typedef {import('../modules/rtdModule/index.js').RtdSubmodule} RtdSubmodule
* @typedef {import('../modules/rtdModule/index.js').adUnit} adUnit
Expand Down Expand Up @@ -446,7 +448,7 @@ function storeRequestInAdagioNS(bid, config) {
bidderRequestsCount,
ortb2: ortb2Data,
ortb2Imp: ortb2ImpData,
localPbjs: '$$PREBID_GLOBAL$$',
localPbjs: getGlobalVarName(),
localPbjsRef: getGlobal(),
organizationId,
site
Expand Down
6 changes: 4 additions & 2 deletions modules/amxBidAdapter.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,8 @@ import { getStorageManager } from '../src/storageManager.js';
import { fetch } from '../src/ajax.js';
import { getGlobal } from '../src/prebidGlobal.js';

import {getGlobalVarName} from '../src/buildOptions.js';

const BIDDER_CODE = 'amx';
const storage = getStorageManager({ bidderCode: BIDDER_CODE });
const SIMPLE_TLD_TEST = /\.com?\.\w{2,4}$/;
Expand Down Expand Up @@ -343,7 +345,7 @@ export const spec = {
trc: fbid.bidRequestsCount || 0,
tm: isTrue(testMode),
V: '$prebid.version$',
vg: '$$PREBID_GLOBAL$$',
vg: getGlobalVarName(),
i: testMode && tagId != null ? tagId : getID(loc),
l: {},
f: 0.01,
Expand Down Expand Up @@ -551,7 +553,7 @@ export const spec = {
U: getUIDSafe(),
re: ref,
V: '$prebid.version$',
vg: '$$PREBID_GLOBAL$$',
vg: getGlobalVarName(),
};
}

Expand Down
4 changes: 3 additions & 1 deletion modules/amxIdSystem.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import {getStorageManager} from '../src/storageManager.js';
import {MODULE_TYPE_UID} from '../src/activities/modules.js';
import {domainOverrideToRootDomain} from '../libraries/domainOverrideToRootDomain/index.js';

import {getGlobalVarName} from '../src/buildOptions.js';

const NAME = 'amxId';
const GVL_ID = 737;
const ID_KEY = NAME;
Expand Down Expand Up @@ -117,7 +119,7 @@ export const amxIdSubmodule = {

v: '$prebid.version$',
av: version,
vg: '$$PREBID_GLOBAL$$',
vg: getGlobalVarName(),
us_privacy: usp,
am: getBidAdapterID(),
gdpr: consent.gdprApplies ? 1 : 0,
Expand Down
4 changes: 3 additions & 1 deletion modules/gamAdServerVideo.js
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,8 @@ import {DEFAULT_GAM_PARAMS, GAM_ENDPOINT, gdprParams} from '../libraries/gamUtil
import { vastLocalCache } from '../src/videoCache.js';
import { fetch } from '../src/ajax.js';
import XMLUtil from '../libraries/xmlUtils/xmlUtils.js';

import {getGlobalVarName} from '../src/buildOptions.js';
/**
* @typedef {Object} DfpVideoParams
*
Expand Down Expand Up @@ -74,7 +76,7 @@ export const VAST_TAG_URI_TAGNAME = 'VASTAdTagURI';
*/
export function buildGamVideoUrl(options) {
if (!options.params && !options.url) {
logError(`A params object or a url is required to use $$PREBID_GLOBAL$$.adServers.gam.buildVideoUrl`);
logError(`A params object or a url is required to use ${getGlobalVarName()}.adServers.gam.buildVideoUrl`);
return;
}

Expand Down
4 changes: 3 additions & 1 deletion modules/liveIntentAnalyticsAdapter.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,14 @@ import { getRefererInfo } from '../src/refererDetection.js';
import { config as prebidConfig } from '../src/config.js';
import { auctionManager } from '../src/auctionManager.js';

import {getGlobalVarName} from '../src/buildOptions.js';

const ANALYTICS_TYPE = 'endpoint';
const URL = 'https://wba.liadm.com/analytic-events';
const GVL_ID = 148;
const ADAPTER_CODE = 'liveintent';
const { AUCTION_INIT, BID_WON } = EVENTS;
const INTEGRATION_ID = '$$PREBID_GLOBAL$$';
const INTEGRATION_ID = getGlobalVarName();

let partnerIdFromUserIdConfig;
let sendAuctionInitEvents;
Expand Down
4 changes: 3 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@
"./modules/*": "./dist/src/public/*.js",
"./metadata/*.js": "./dist/src/metadata/modules/*.js",
"./metadata/*.json": "./metadata/modules/*.json",
"./metadata/*": "./dist/src/metadata/modules/*.js"
"./metadata/*": "./dist/src/metadata/modules/*.js",
"./customize/*.mjs": "./customize/*.mjs",
"./customize/*": "./customize/*.mjs"
},
"scripts": {
"serve": "gulp serve",
Expand Down
24 changes: 17 additions & 7 deletions plugins/pbjsGlobals.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,14 @@ const {buildOptions} = require('./buildOptions.js');
const FEATURES_GLOBAL = 'FEATURES';

module.exports = function(api, options) {
const {pbGlobal, defineGlobal, features, distUrlBase, skipCalls} = buildOptions(options);
const {features, distUrlBase, skipCalls} = buildOptions(options);

let replace = {
'$prebid.version$': prebid.version,
'$$PREBID_GLOBAL$$': pbGlobal,
'$$DEFINE_PREBID_GLOBAL$$': defineGlobal,
'$$PREBID_GLOBAL$$': false,
'$$DEFINE_PREBID_GLOBAL$$': false,
'$$REPO_AND_VERSION$$': `${prebid.repository.url.split('/')[3]}_prebid_${prebid.version}`,
'$$PREBID_DIST_URL_BASE$$': distUrlBase,
'$$PREBID_DIST_URL_BASE$$': false,
'$$LIVE_INTENT_MODULE_MODE$$': (process && process.env && process.env.LiveConnectMode) || 'standard'
};

Expand Down Expand Up @@ -49,6 +50,12 @@ module.exports = function(api, options) {
}
}

function checkMacroAllowed(name) {
if (replace[name] === false) {
throw new Error(`The macro ${name} should no longer be used; look for a replacement in src/buildOptions.ts`)
}
}

return {
visitor: {
Program(path, state) {
Expand All @@ -66,22 +73,24 @@ module.exports = function(api, options) {
},
ImportDeclaration: translateToJs,
ExportDeclaration: translateToJs,
StringLiteral(path) {
StringLiteral(path, state) {
Object.keys(replace).forEach(name => {
if (path.node.value.includes(name)) {
checkMacroAllowed(name);
path.node.value = path.node.value.replace(
new RegExp(escapeRegExp(name), 'g'),
replace[name].toString()
);
}
});
},
TemplateLiteral(path) {
TemplateLiteral(path, state) {
path.traverse({
TemplateElement(path) {
Object.keys(replace).forEach(name => {
['raw', 'cooked'].forEach(type => {
if (path.node.value[type].includes(name)) {
checkMacroAllowed(name);
path.node.value[type] = path.node.value[type].replace(
new RegExp(escapeRegExp(name), 'g'),
replace[name]
Expand All @@ -92,9 +101,10 @@ module.exports = function(api, options) {
}
});
},
Identifier(path) {
Identifier(path, state) {
Object.keys(replace).forEach(name => {
if (path.node.name === name) {
checkMacroAllowed(name);
if (identifierToStringLiteral.includes(name)) {
path.replaceWith(
t.StringLiteral(replace[name])
Expand Down
16 changes: 16 additions & 0 deletions src/buildOptions.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-expect-error
// eslint-disable-next-line prebid/validate-imports
import buildOptions from "../buildOptions.mjs"; // autogenerated during precompilation

export function getGlobalVarName(): string {
return buildOptions.pbGlobal;
}

export function shouldDefineGlobal(): boolean {
return buildOptions.defineGlobal;
}

export function getDistUrlBase(): string {
return buildOptions.distUrlBase;
}
Loading
Loading