transform-dev.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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. const babel = require('@babel/core');
  20. const parser = require('@babel/parser');
  21. function transformDEVPlugin ({types, template}) {
  22. return {
  23. visitor: {
  24. Identifier: {
  25. enter(path, state) {
  26. if (path.isIdentifier({ name: '__DEV__' }) && path.scope.hasGlobal('__DEV__')) {
  27. path.replaceWith(
  28. parser.parseExpression(state.opts.expr)
  29. );
  30. }
  31. }
  32. }
  33. }
  34. };
  35. };
  36. module.exports.transform = function (sourceCode, sourcemap, expr) {
  37. let {code, map} = babel.transformSync(sourceCode, {
  38. plugins: [ [transformDEVPlugin, {
  39. expr: expr || 'process.env.NODE_ENV !== \'production\''
  40. }] ],
  41. compact: false,
  42. sourceMaps: sourcemap
  43. });
  44. return {code, map};
  45. };
  46. /**
  47. * @param {string} code
  48. * @throws {Error} If check failed.
  49. */
  50. module.exports.recheckDEV = function (code) {
  51. return code.indexOf('process.env.NODE_ENV') >= 0;
  52. };