経験は何よりも饒舌

10年後に真価を発揮するかもしれないブログ 

Rethinking about role of Babel and webpack

I rethink about role of Babel and webpack.
Initial state of my code is here.

First, don't use webpack or Babel.
It means edit index.html as below.

<!DOCTYPE html>
<html>
...
<body>
<script src="../src/js/app.js"></script>
</body>
</html>
```

When previewed it in the browser(Chrome), get the following error.

This error can be resolved by applying the module to HTML as follows.
JavaScript modules - JavaScript | MDN

<!DOCTYPE html>
<html>
...
<body>
<script type="module" src="../src/js/app.js"></script>
</body>
</html>
```

But, got different error as below.

This error occured because violates the restrictions of the same origin policy.

It means file:///Users/tagawahirotaka/Desktop/webpack-tutorial/public/index.html that displayed in the browser and file:///Users/tagawahirotaka/Desktop/webpack-tutorial/src/js/app.js that call JavaScript violates the restrictions of the same origin policy.

Same-origin policy - Web security | MDN
https://developer.mozilla.org/en-US/docs/Archive/Misc_top_level/Same-origin_policy_for_file:_URIs


Second, use webpack and don't use Babel.
It means edit index.html as below.

<!DOCTYPE html>
<html>
...
<body>
<script src="js/bundle.js"></script>
</body>
</html>
```

When previewed it in the browser, get the results you want.

Because js/bundle.js is file that starting from the specified file (src/js /app.js), the files are connected in a Imozuru formula by relying on the import statement, and they are combined into one JavaScript file by webpack.

One question arises here.
I wonder why import works without Babel when it should be ES2015(ES6) statement.

It because webpack resolves import dependencies.
Modules | webpack

In contrast to Node.js modules, webpack modules can express their dependencies in a variety of ways. A few examples are:

  • An ES2015 import statement

...

In other words, there is no need to rewrite import to require with babel.
Babel · The compiler for next generation JavaScript

So, when Babel plays a role?
Edit src/js/modules/addition.js as below.

const add = (num1, num2) => {
    return num1 + num2;
}

export default add;

Arrow function expressions used in this code is an ES2015(ES6) statement.
When bundle this code by webpack without babel, get the results you want.

This is because Chrome supports the arrow functions in ES2015(ES6) statement.
Arrow function expressions - JavaScript | MDN


In the conclusion, I understand two things.

  • webpack combine the scattered modules into one file based on the import statement.
  • Babel rewrites ES2015(ES6) statement to earlier statement, but import is supported by webpack, and Chrome and other browser is also compatible with ES2015(ES6) statement.