UNPKG

1.84 kBJavaScriptView Raw
1/*
2* Licensed to the Apache Software Foundation (ASF) under one
3* or more contributor license agreements. See the NOTICE file
4* distributed with this work for additional information
5* regarding copyright ownership. The ASF licenses this file
6* to you under the Apache License, Version 2.0 (the
7* "License"); you may not use this file except in compliance
8* with the License. You may obtain a copy of the License at
9*
10* http://www.apache.org/licenses/LICENSE-2.0
11*
12* Unless required by applicable law or agreed to in writing,
13* software distributed under the License is distributed on an
14* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15* KIND, either express or implied. See the License for the
16* specific language governing permissions and limitations
17* under the License.
18*/
19
20const babel = require('@babel/core');
21const parser = require('@babel/parser');
22
23function transformDEVPlugin ({types, template}) {
24 return {
25 visitor: {
26 Identifier: {
27 enter(path, state) {
28 if (path.isIdentifier({ name: '__DEV__' }) && path.scope.hasGlobal('__DEV__')) {
29 path.replaceWith(
30 parser.parseExpression(state.opts.expr)
31 );
32 }
33 }
34 }
35 }
36 };
37};
38
39
40module.exports.transform = function (sourceCode, sourcemap, expr) {
41 let {code, map} = babel.transformSync(sourceCode, {
42 plugins: [ [transformDEVPlugin, {
43 expr: expr || 'process.env.NODE_ENV !== \'production\''
44 }] ],
45 compact: false,
46 sourceMaps: sourcemap
47 });
48
49 return {code, map};
50};
51
52/**
53 * @param {string} code
54 * @throws {Error} If check failed.
55 */
56module.exports.recheckDEV = function (code) {
57 return code.indexOf('process.env.NODE_ENV') >= 0;
58};