UNPKG

2.44 kBJavaScriptView Raw
1"use strict";
2/**
3 * @license
4 * Copyright (c) 2018 The Polymer Project Authors. All rights reserved.
5 * This code may only be used under the BSD style license found at
6 * http://polymer.github.io/LICENSE.txt
7 * The complete set of authors may be found at
8 * http://polymer.github.io/AUTHORS.txt
9 * The complete set of contributors may be found at
10 * http://polymer.github.io/CONTRIBUTORS.txt
11 * Code distributed by Google as part of the polymer project is also
12 * subject to an additional IP rights grant found at
13 * http://polymer.github.io/PATENTS.txt
14 */
15Object.defineProperty(exports, "__esModule", { value: true });
16const plugin_syntax_import_meta_1 = require("@babel/plugin-syntax-import-meta");
17const template_1 = require("@babel/template");
18const ast = template_1.default.ast;
19/**
20 * Rewrites `import.meta`[1] into an import for a module named "meta". It is
21 * expected this plugin runs alongside @babel/plugin-transform-modules-amd which
22 * will transform this import into an AMD dependency, and is loaded using
23 * @polymer/esm-amd-loader which will provide an object with a `url`[2] property
24 * for the "meta" dependency.
25 *
26 * [1]: https://github.com/tc39/proposal-import-meta
27 * [2]: https://html.spec.whatwg.org/#hostgetimportmetaproperties
28 */
29exports.rewriteImportMeta = {
30 inherits: plugin_syntax_import_meta_1.default,
31 visitor: {
32 Program(path) {
33 const metas = [];
34 const identifiers = new Set();
35 path.traverse({
36 MetaProperty(path) {
37 const node = path.node;
38 if (node.meta && node.meta.name === 'import' &&
39 node.property.name === 'meta') {
40 metas.push(path);
41 for (const name of Object.keys(path.scope.getAllBindings())) {
42 identifiers.add(name);
43 }
44 }
45 }
46 });
47 if (metas.length === 0) {
48 return;
49 }
50 let metaId = 'meta';
51 while (identifiers.has(metaId)) {
52 metaId = path.scope.generateUidIdentifier('meta').name;
53 }
54 path.node.body.unshift(ast `import * as ${metaId} from 'meta';`);
55 for (const meta of metas) {
56 meta.replaceWith(ast `${metaId}`);
57 }
58 },
59 }
60};
61//# sourceMappingURL=babel-plugin-import-meta.js.map
\No newline at end of file