Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

import statement returns undefined #62

Closed
erichulburd opened this issue Mar 28, 2016 · 7 comments
Closed

import statement returns undefined #62

erichulburd opened this issue Mar 28, 2016 · 7 comments

Comments

@erichulburd
Copy link

I'm trying to use this plugin to compile react templates on the server - see the webpack plugin.

Here are my configuration settings.

server/config/webpack.js

module.exports = {
  output: {
    libraryTarget: 'commonjs'
  },
  module: {
    loaders: [
      {
        test: /\.template\.html$/,
        loaders: ["react-templates-loader?targetVersion=0.14.0"]
      },
    ],
  },
};

.babelrc

{
  "presets": ["es2015", "react"],
  "plugins": [
    ["babel-plugin-webpack-loaders",
      { "config": "./server/config/webpack.js",
        "verbose": false } ]
  ]
}

An example template:
components/layout/layout.template.html

<div id="layout">
  <h1>Basic Layout Component</h1>
  <div rt-if="!this.state.example" class="alert alert-warning">
    Choose an example.
  </div>
  <div rt-if="this.state.example" class="alert alert-info">
    {this.state.example.introduce()}
  </div>
  <div class="btn-group" role="group">
    <button
      rt-repeat="example in this.examples"
      key="{example.scoped_id}"
      data-param="example_id"
      data-value="{example.data.id}"
      rt-class="{active: this.example && this.example.data.id === example.data.id}"
      onClick="{this.setParam.bind(this)}"
      type="button" class="btn btn-primary">{example.data.name}</button>
  </div>
</div>

And the related React Component:
components/layout/layout.component.js

import React from 'react';
import template from 'layout.template.html';

class Layout extends React.Component {
  // ...
  render(){
   // note this works as intended when compiled with pure Webpack.
  console.log(template);
   return template.call(this);
  }
}

Unfortunately, template is undefined when I run with this plugin. In fact, I've put some log statements into node_modules/react-templates-loader/index.js and it seems the loader is never even called.

I'd be willing to put some time into making this work, but I really don't where to start. Do you have any idea where to start in terms of debugging this?

@erichulburd
Copy link
Author

Update

I think the issue is that all of the loaders mentioned in the readme are supposed to return strings. With React Templates, I'm really trying to return a Javascript function. With the following webpack configuration,

module.exports = {
  output: {
    libraryTarget: 'commonjs'
  },
  module: {
    loaders: [
      {
        test: /\.template\.html$/,
        loaders: ["raw", "react-templates-loader?targetVersion=0.14.7&modules=jsrt"]
      },
    ],
  },
};

I get the following output for template:

(function () {
 function repeatExample1(example,exampleIndex) {
        return React.createElement('button',{"key" : (example.scoped_id),"data-param" : "example_id","data-value" : (example.data.id),"className" : _.keys(_.pick({active: this.example && this.example.data.id === example.data.id}, _.identity)).join(" ") + " " + "btn btn-primary","onClick" : (this.setParam.bind(this)),"type" : "button"},(example.data.name))
        }

 return function(){
return React.createElement('div',{"id" : "layout"},React.createElement('h1',{},"Basic Layout Component"),((!this.state.example)?(React.createElement('div',{"className" : "alert alert-warning"},"\n    Choose an example.\n  ")):null),((this.state.example)?(React.createElement('div',{"className" : "alert alert-info"},"\n    ",(this.state.example.introduce()),"\n  ")):null),React.createElement.apply(this, ['div',{"className" : "btn-group","role" : "group"},_.map(this.examples,repeatExample1.bind(this))]))}}
)()

This is close to what we want, but of course React won't be defined. Alternatively, passing the modules=commonjs flag to React Templates, I get the following result:

'use strict';
var React = require('react/addons');
var _ = require('lodash');
function repeatExample1(example, exampleIndex) {
    return React.createElement(button, {
        'key': example.scoped_id,
        'data-param': 'example_id',
        'data-value': example.data.id,
        'className': _.keys(_.pick({ active: this.example && this.example.data.id === example.data.id }, _.identity)).join(' ') + ' ' + 'btn btn-primary',
        'onClick': this.setParam.bind(this),
        'type': 'button'
    }, example.data.name);
}
module.exports = function () {
    return React.createElement(div, { 'id': 'layout' }, React.createElement(h1, {}, 'Basic Layout Component'), !this.state.example ? React.createElement(div, { 'className': 'alert alert-warning' }, '\n    Choose an example.\n  ') : null, this.state.example ? React.createElement(div, { 'className': 'alert alert-info' }, '\n    ', this.state.example.introduce(), '\n  ') : null, React.createElement.apply(this, [
        div,
        {
            'className': 'btn-group',
            'role': 'group'
        },
        _.map(this.examples, repeatExample1.bind(this))
    ]));
};

This leads to a more general question, what needs to happen to load Javascript modules?

@erichulburd
Copy link
Author

Update 2

I've tried returning the various strings with a plugin:

module.exports = {yada: 'yada'};

// import result
{yada: 'yada'}
var yada = "yada";
module.exports = {yada: yada};

// import result
ReferenceError: yada is not defined
module.exports = 'Hello ' + ' world!';

// import result
'Hello world!'
module.exports = function(){ return 'yada' }

// import result
undefined

So for some reason, difficulty arises:

  • when the returned source code does not set module.exports on the first line.
  • when module.exports is a function.

@istarkov
Copy link
Owner

I think of Ioaders as about resources in other languages, resources is just simple types like plain objects, strings, numbers. Not functions.
Webpack loaders allows you to return anything, I can't support all of variations users can return from their loaders. It just supports plugins I really use in my work. There are situations in which it is impossible to just replace require with module.exports.
This plugin was written in a few hours, and I really have no time to support all webpack plugins from community.
Any PRs are welcome.

@erichulburd
Copy link
Author

I see, and after reading the source code, it would be really unreasonable to expect you (or really anyone) to.

I think it makes sense to do what I want to do with a separate plugin. Thanks.

@erichulburd
Copy link
Author

@istarkov I have one question for you that would be a huge help. I'm not quite grasping how this plugin gains access to css files before Babel tries to parse it to AST.

For instance, when you call var css = require('example.css'), normally this would throw a parse error when transpiling with Babel. How is it your plugin runs compiles this file before Babel does?

@istarkov
Copy link
Owner

As it is a babel plugin I could parse AST tree before any javascript will execute.
The main idea is in this line https://github.com/istarkov/babel-plugin-webpack-loaders/blob/master/src/plugin.js#L190

Any require (and import as import converted to require with other plugins) call which confirms this and some criteria below, processed and transformed by this plugin.

@erichulburd
Copy link
Author

Ok, this has nothing to do with your repo, so I'll close and leave this comment here for posterity. Thanks.

Trying to write another plugin that compiles html files, much as this one parses css files. However, I kept getting SyntaxError: Unexpected token. The ES2015 preset was trying to work on the html file before my plugin compiled it. However, I was only getting this error some of the time (90% let's say).

I defined my visitor as follows:

module.exports = function (opts) {
    return {
        visitor: {
            CallExpression: {
              enter(path, opts) {
              // do stuff to html
            }
          }
      }
    };
};

My problem is that plugin/preset order is not respected in Babel6 (see discussion) - though there is an experimental feature to try to resolve this: babel/babel#3281

What's weird though, is your repo doesn't have this issue - even after I bumped the babel-core version in my repo to "^6.5.2", I still get this error sporadically.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants