Skip to content

Commit

Permalink
add replace plugin (#128)
Browse files Browse the repository at this point in the history
  • Loading branch information
Rich-Harris authored Dec 16, 2021
1 parent 2db9bf9 commit 95b3af8
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 1 deletion.
11 changes: 10 additions & 1 deletion packages/repl/src/lib/workers/bundler/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import * as rollup from 'rollup/dist/es/rollup.browser.js';
import commonjs from './plugins/commonjs.js';
import glsl from './plugins/glsl.js';
import json from './plugins/json.js';
import replace from './plugins/replace.js';

self.window = self; // egregious hack to get magic-string to work in a worker

Expand Down Expand Up @@ -229,7 +230,15 @@ async function get_bundle(uid, mode, cache, lookup) {
try {
bundle = await rollup.rollup({
input: './App.svelte',
plugins: [repl_plugin, commonjs, json, glsl],
plugins: [
repl_plugin,
commonjs,
json,
glsl,
replace({
'process.env.NODE_ENV': JSON.stringify('production')
})
],
inlineDynamicImports: true,
onwarn(warning) {
all_warnings.push({
Expand Down
58 changes: 58 additions & 0 deletions packages/repl/src/lib/workers/bundler/plugins/replace.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
function escape(str) {
return str.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');
}

function ensureFunction(functionOrValue) {
if (typeof functionOrValue === 'function') {
return functionOrValue;
}
return function () {
return functionOrValue;
};
}

function longest(a, b) {
return b.length - a.length;
}

function mapToFunctions(object) {
return Object.keys(object).reduce(function (functions, key) {
functions[key] = ensureFunction(object[key]);
return functions;
}, {});
}

function replace(options) {
const functionValues = mapToFunctions(options);
const keys = Object.keys(functionValues).sort(longest).map(escape);

const pattern = new RegExp('\\b(' + keys.join('|') + ')\\b', 'g');

return {
name: 'replace',

transform: function transform(code, id) {
let hasReplacements = false;
let match;
let start;
let end;
let replacement;

code = code.replace(pattern, (_, key) => {
hasReplacements = true;
return String(functionValues[key](id));
});

if (!hasReplacements) {
return null;
}

return {
code,
map: null
};
}
};
}

export default replace;

1 comment on commit 95b3af8

@vercel
Copy link

@vercel vercel bot commented on 95b3af8 Dec 16, 2021

Choose a reason for hiding this comment

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

Please sign in to comment.