MCPcopy Create free account
hub / github.com/rollup/plugins / transform

Function transform

packages/inject/src/index.js:87–207  ·  view source on GitHub ↗
(code, id)

Source from the content-addressed store, hash-verified

85 name: 'inject',
86
87 transform(code, id) {
88 if (!filter(id)) return null;
89 if (code.search(firstpass) === -1) return null;
90
91 if (sep !== '/') id = id.split(sep).join('/'); // eslint-disable-line no-param-reassign
92
93 let ast = null;
94 try {
95 ast = this.parse(code);
96 } catch (err) {
97 this.warn({
98 code: 'PARSE_ERROR',
99 message: `@rollup/plugin-inject: failed to parse ${id}. Consider restricting the plugin to particular files via options.include`
100 });
101 }
102 if (!ast) {
103 return null;
104 }
105
106 const imports = new Set();
107 ast.body.forEach((node) => {
108 if (node.type === 'ImportDeclaration') {
109 node.specifiers.forEach((specifier) => {
110 imports.add(specifier.local.name);
111 });
112 }
113 });
114
115 // analyse scopes
116 let scope = attachScopes(ast, 'scope');
117
118 const magicString = new MagicString(code);
119
120 const newImports = new Map();
121
122 function handleReference(node, name, keypath) {
123 let mod = modulesMap.get(keypath);
124 if (mod && !imports.has(name) && !scope.contains(name)) {
125 if (typeof mod === 'string') mod = [mod, 'default'];
126
127 // prevent module from importing itself
128 if (mod[0] === id) return false;
129
130 const hash = `${keypath}:${mod[0]}:${mod[1]}`;
131
132 const importLocalName =
133 name === keypath ? name : makeLegalIdentifier(`$inject_${keypath}`);
134
135 if (!newImports.has(hash)) {
136 // escape apostrophes and backslashes for use in single-quoted string literal
137 const modName = mod[0].replace(/[''\\]/g, '\\$&');
138 if (mod[1] === '*') {
139 newImports.set(hash, `import * as ${importLocalName} from '${modName}';`);
140 } else {
141 newImports.set(hash, `import { ${mod[1]} as ${importLocalName} } from '${modName}';`);
142 }
143 }
144

Callers

nothing calls this directly

Calls 3

attachScopesFunction · 0.90
valuesMethod · 0.80
filterFunction · 0.50

Tested by

no test coverage detected