Alberto Centelles
Alberto Centelles

Reputation: 1253

Babel convert path jsx to js

I am using babel to transpile some es2015 code to es5, like this:

"scripts": {
    "build:lib": "babel src --out-dir lib --presets=react,es2015,stage-0",
    "clean": "rimraf lib dist coverage",
    "prepublish": "npm run clean && npm run build:lib" 
}

It is converting it fine to es5. The problem is that babel is not changing the path among files. It changes the extension of the file from .jsx to .js, but inside the file, it is still referencing the file as .jsx.

To simplify it, the folder structure looks like this. Babel has changed the extensions of the .jsx files:

- index.js
- Component.js

While inside index.js, it is doing keeping the .jsx extension:

require('./Component.jsx');

Am I missing something? Is there a better way to do this? Thanks for you help:)

Upvotes: 0

Views: 624

Answers (2)

Alberto Centelles
Alberto Centelles

Reputation: 1253

As Shiroo suggested, I ended up using webpack for this. The key concept here was understanding what resolvers do. They are really well explained in the webpack docs: https://webpack.github.io/docs/resolving.html

  resolve: {
    root: path.resolve('./src'),
    extensions: ['', '.js', '.jsx']
  }

Later, I encountered that all the node_modules were also included in the bundle, despite having it explicitly inside the loader:

module: {
    loaders: [
      {
        test: /(\.jsx|\.js)$/,
        include: path.resolve('./src'),
        exclude: /node_modules/,
        loader: 'babel'
      }
    ]
  }

This issue is better explained here https://stackoverflow.com/a/35820388/4929834

Upvotes: 0

Shiroo
Shiroo

Reputation: 666

Why won't you simply use Webpack for that? Is there a reason for that? especially that you are also missing setting up node_env production so it will avoid adding propTyping etc.

es3ify is just for changing the code, while you are trying to build a library out of it. you need a tree builder like Webpack for something like that (how es3ify would know about the references between each other?)

So tl;dr there is a better solution for that: use Webpack.

module.exports = {
  devtool: 'source-map',

  entry: [
    path.join(__dirname, '/src/index.jsx')
  ],

  output: {
    path: path.join(__dirname, '/dist'),
    filename: 'bundle.js',
    publicPath: '/'
  },

  resolve: {
    extensions: ['', '.js', '.jsx']
  },

  module: {
    loaders: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        loader: 'babel'
      }
    ]
  },

  plugins: [
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify(process.env.NODE_ENV)
      }
    }),
    new webpack.optimize.UglifyJsPlugin({
      compressor: {
        warnings: false
      }
    })
  ]
};

Upvotes: 1

Related Questions