Babel and ES6 modules

Hello,

When I want to use import babel transpile it to
var moduleName = require("moduleName");
I guess require is Node thing, how can I solve this problem?
I’m making client-side JS modules.

What are you wanting it to be instead?

I just googled and saw one article that says I need module loader, I will use requireJS as it’s easiest to learn.
Did I get it right?

Yes, requireJS is a good solution.

1 Like

You should use Webpack or another compiler. Using require or import in the browser is still listed as an experimental feature.

RequireJS is considered to be an antiquated library. I would not suggest it. Use a compiler instead.

4 Likes

I never used requireJS, but in its most basic form webpack is actually quite simple too… install it like

yarn add webpack -D

and run like e.g.

yarn webpack src/index.js dist/bundle.js

and that’s it. If you’re using babel, you can install the following dependencies

yarn add babel-loader babel-core babel-preset-env -D

and then transpile your code in one go like so:

yarn webpack src/index.js dist/bundle.js --module-bind js=babel-loader

As your configuration is getting more complex (minification, source maps, tree shaking etc.) you’ll want to put that in a dedicated config file, but for some basic bundling like above that’s not really necessary.

Note though that if you’re only writing the modules themselves (e.g. for publishing on npm), then you wouldn’t bundle anything; just require() the internal dependencies as usual and export it via module.exports. It’s then up to the consumer of the module to choose an appropriate way to handle dependencies.

2 Likes

Thank you everyone, you really helped me guys! :slight_smile:

1 Like

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.