Babel transpiles' import 'to' require ', but' require is not used in ecma5

As far as I understand, using Babel allows you to use ecma6 javascript in ecma5 by transpilation. However, when I use "import", "import" translates to "require". "require" is not ecma5 and requires the library "require.js". Therefore, you cannot use import / export without additional dependencies, is this correct?

+6
source share
2 answers

Yes, Babel is only intended to translate new language features compatible with modern javascript engines. Babel does not compile import require.js syntax. Rather, it uses the CommonJS module syntax used by Node.js. This way you can run the code directly without additional build dependencies in Node.js.

Since it works with single files at the same time and is a direct translation, it makes no decisions about how you want to include the source code of these other files in the current one.

However, if you intend to use it in a browser, you will need a build system or assembler that supports CommonJS module instructions:

  • See https://babeljs.io/docs/setup/#installation for a list of many typical build configurations.
  • Browserify and Webpack are two of the most popular in the Javacript ecosystem.
  • These systems combine your javascript code by inserting files wherever "required" is required, and usually produce a single js output file that you can run in ecma5
+5
source

Try replacing the query in the translation code with the appropriate method. Example: for me, replace require ("react") with window.react will work

0
source

All Articles