最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Babel transpiles 'import' to 'require', but 'require isn't useable

programmeradmin2浏览0评论

It was my understanding that use Babel allows you to use ecma6 javascript in an ecma5 environment by transpiling. When I use 'import' however, the 'import' is transpilied to 'require'. 'require' isn't ecma5 and requires the library 'require.js'. Therefore you can't use 'import/ export' without additional dependencies, is this correct?

It was my understanding that use Babel allows you to use ecma6 javascript in an ecma5 environment by transpiling. When I use 'import' however, the 'import' is transpilied to 'require'. 'require' isn't ecma5 and requires the library 'require.js'. Therefore you can't use 'import/ export' without additional dependencies, is this correct?

Share Improve this question edited Jul 3, 2016 at 7:49 Honinbo Shusaku 1,5113 gold badges28 silver badges47 bronze badges asked Jul 3, 2016 at 3:35 Brad WoodsBrad Woods 1,5462 gold badges14 silver badges31 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 18

Yes, Babel is just intended for translating new language features to be compatible with modern javascript engines. Babel doesn't compile to require.js module import syntax. Rather it uses the CommonJS module syntax as used by Node.js. So you could run the code directly without further build dependencies in Node.js.

As it operates on single files at a time and is a straight forward translation, it doesn't make any decisions as to how you want to include the source code of those other files into the current one.

That said, if you are going to use it in browser, you will need a build system or bundler that supports CommonJS modules statements:

  • See https://babeljs.io/docs/setup/#installation for a list of many typical build configurations
  • Browserify and Webpack are two of the most popular ones in the Javacript ecosystem
  • These systems 'bundle' your javascript code by injecting files wherever 'require' is referenced and thus typically produce one output js file which you can run in ecma5

Try to replace require in transpilied code by a correspondent method. Ex: For me, replace require('react') by window.react will work

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论