Class: Condenser::BabelProcessor

Inherits:
NodeProcessor show all
Defined in:
lib/condenser/processors/babel_processor.rb

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from NodeProcessor

#binary, #exec_runtime, #exec_runtime_error, #exec_syntax_error, node_modules_path, #node_modules_path, setup

Constructor Details

#initialize(options = {}) ⇒ BabelProcessor

Returns a new instance of BabelProcessor.



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/condenser/processors/babel_processor.rb', line 11

def initialize(options = {})
  @options = {
    ast: false,
    compact: false,
    plugins: [
      ["#{node_modules_path}/babel-plugin-transform-class-extended-hook", {}],
      ["#{node_modules_path}/@babel/plugin-proposal-class-properties", {}],
      ["#{node_modules_path}/@babel/plugin-transform-runtime", {
        corejs: 3,
        useESModules: true
      }],
    ],
    presets: [["#{File.expand_path('../node_modules', __FILE__)}/@babel/preset-env", {
      "modules": false,
      "targets": { "browsers": "> 1% and not dead" }
      # "useBuiltIns": 'usage',
      # corejs: { version: 3, proposals: true }
    } ]],
    sourceMap: false
  }.merge(options)
end

Class Method Details

.call(environment, input) ⇒ Object

npm install @babel/core @babel/runtime-corejs3 @babel/plugin-transform-runtime @babel/preset-env rollup rollup-plugin-commonjs rollup-plugin-node-resolve @babel/plugin-proposal-class-properties babel-plugin-transform-class-extended-hook



7
8
9
# File 'lib/condenser/processors/babel_processor.rb', line 7

def self.call(environment, input)
  new.call(environment, input)
end

Instance Method Details

#call(environment, input) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
# File 'lib/condenser/processors/babel_processor.rb', line 33

def call(environment, input)
  opts = {
    # 'moduleRoot' => nil,
    'filename' => input[:filename],
    'moduleId' => input[:filename].sub(/(\..+)+/, ''),
    'cwd' => '/assets/',
    'filenameRelative' => input[:filename],
    'sourceFileName' => input[:filename]
    # 'sourceMapTarget' => input[:filename]
    # 'inputSourceMap'
  }.merge(@options).select { |k,v| !v.nil? }
  
  result = exec_runtime(<<-JS)
    const babel = require("#{File.expand_path('../node_modules', __FILE__)}/@babel/core");
    const source = #{JSON.generate(input[:source])};
    const options = #{JSON.generate(opts).gsub(/"@?babel[\/-][^"]+"/) { |m| "require(#{m})"}};
    
    let imports = [];
    let defaultExport = false;
    let hasExports = false;
    options['plugins'].push(function({ types: t }) {
      return {
        visitor: {
          ImportDeclaration(path, state) {
            imports.push(path.node.source.value);
          },
          ExportDefaultDeclaration(path, state) {
            hasExports = true;
            defaultExport = true;
          },
          ExportDefaultSpecifier(path, state) {
            hasExports = true;
            defaultExport = true;
          },
          ExportAllDeclaration(path, state) {
            hasExports = true;
          },
          ExportNamedDeclaration(path, state) {
            hasExports = true;
          },
          ExportSpecifier(path, state) {
            hasExports = true;
          },
        }
      };
    });
    
    
    try {
      const result = babel.transform(source, options);
      result.imports = imports;
      result.exports = hasExports;
      result.defaultExport = defaultExport;
      console.log(JSON.stringify(result));
    } catch(e) {
      console.log(JSON.stringify({'error': [e.name, e.message, e.stack]}));
      process.exit(0);
    }
  JS
  
  if result['error']
    if result['error'][0] == 'SyntaxError'
      raise exec_syntax_error(result['error'][1], "/assets/#{input[:filename]}")
    else
      raise exec_runtime_error(result['error'][0] + ': ' + result['error'][1])
    end
  else
    input[:source] = result['code']
    input[:map] = result['map']
    input[:export_dependencies] = result['imports'].map do |i|
      i.end_with?('.js') ? i : "#{i}.js"
    end
    input[:default_export] = result['defaultExport']
    input[:exports] = result['exports']
  end
end

#split_subpath(path, subpath) ⇒ Object

Internal: Get relative path for root path and subpath.

path - String path subpath - String subpath of path

Returns relative String path if subpath is a subpath of path, or nil if subpath is outside of path.



117
118
119
120
121
122
123
124
125
# File 'lib/condenser/processors/babel_processor.rb', line 117

def split_subpath(path, subpath)
  return "" if path == subpath
  path = File.join(path, ''.freeze)
  if subpath.start_with?(path)
    subpath[path.length..-1]
  else
    nil
  end
end