Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compile ES6+ code to ES6 with webpack?

I want to compile my code to ES6 not ES5. Here is my babelrc.

{
"presets": [
    [
        "env",
        {
            "modules": false,
            "useBuiltIns": true,
            "targets": {
                "browsers": ["Chrome >= 60"]
            }
        }
    ],
    ["react"],
    ["stage-2"]
]}

And with babel-cli, the right ES6 code can be compiled. For example

enter image description here

But when I use webpack, babel-loader in the same babel config, my ES6 code was compiled to ES5.

So how can i compile ES6+ code to ES6+ with Webpack?

Does webpack compile ES6+ code to ES5 ?

like image 303
Zhendong Avatar asked Mar 27 '18 07:03

Zhendong


People also ask

How do I use ES6 in webpack config?

Create your scripts in package. json : "scripts": { "test": "echo \"Error: no test specified\" && exit 1", "build": "webpack", "start": "webpack-dev-server --open" }, Run npm run build and npm start .

Does webpack convert ES6 to ES5?

We can now use webpack to bundle our modules and transpile ES6 code down to ES5 with Babel. However, it's a bit of a niggle that, to transpile our ES6 code, we have to run npm run build every time we make a change.

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.


Video Answer


1 Answers

There's option target option esmodules. check it out here.

{
"presets": [
    [
        "@babel/preset-env",
        {
            "modules": false,
            "useBuiltIns": true,
            "targets": {
                "browsers": ["Chrome >= 60"],
                "esmodules": true
            }
        }
    ],
    ["@babel/preset-react"]
]}
like image 57
Jasper Bernales Avatar answered Oct 20 '22 08:10

Jasper Bernales