Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReactJS.net - How do I use ES6 modules

Tags:

reactjs.net

I have ReactJS.Net successfully running, including using ES6 syntax.

I am using the default Jsx transformation pipeline, which is using Babel. Looking at source in the browser I can see that ES6 code has been converted to ES5 by ReactJS.Net

I have been unable to get modules working.

The browser gives me 2 errors:

Uncaught ReferenceError: exports is not defined
Uncaught ReferenceError: require is not defined

How do I use ES6 Modules?

Simplest example:

Lib.js

export function square(x) {
    return x * x;
}

UserOfLib.js

import { square } from 'Lib';
console.log(square(11)); 

Gets transformed to this (looking at browser source):

Lib:

// @hash v3-AD133907ABEC5D32B3768A3AF2301FC9
// Automatically generated by ReactJS.NET. Do not edit, your changes will be overridden.
// Version: 2.0.1 (build 5e9476a)
// Generated at: 08-Nov-15 6:40:26 AM
///////////////////////////////////////////////////////////////////////////////
Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.square = square;

function square(x) {
    return x * x;
}

UserOfLib:

// @hash v3-812C209AFED25C2B4507E5769B0D899B
// Automatically generated by ReactJS.NET. Do not edit, your changes will be overridden.
// Version: 2.0.1 (build 5e9476a)
// Generated at: 08-Nov-15 6:40:26 AM
///////////////////////////////////////////////////////////////////////////////
var _Lib = require('Lib');

console.log((0, _Lib.square)(11)); // 121
like image 371
zadam Avatar asked Nov 07 '15 21:11

zadam


People also ask

Why we use webpack in ReactJS?

Webpack is the recommended bundling solution and should be preferred over Cassette or ASP.NET Bundling. Your project will bundle its own copy of react and react-dom with webpack, and ReactJS.NET will be used only for server-side rendering. Copy from the sample project to the root of your project: package.

Do I need webpack for ES6 modules?

For most browsers, yes, you can accomplish getting all needed code to the browser with just ES6 modules, without Webpack.

What are ES6 modules?

Modules are the piece or chunk of a JavaScript code written in a file. JavaScript modules help us to modularize the code simply by partitioning the entire code into modules that can be imported from anywhere. Modules make it easy to maintain the code, debug the code, and reuse the piece of code.


1 Answers

Currently, ReactJS.Net does not handle modules. If you want to use modules, you'll need to use a module bundler such as Webpack or Browserify to compile the modules down to vanilla JavaScript. Implementing support for modules in ReactJS.NET itself is a non-trivial amount of work, since it'd need to deal with dependencies and loading modules in the correct order, and good well-tested solutions like Webpack already exist.

like image 66
Daniel Lo Nigro Avatar answered Oct 13 '22 02:10

Daniel Lo Nigro