Weved
Weved

Reputation: 823

webpack can convert js to es6?

I using webpack to bundle my node application.

I see the result in the bundle that webpack convert from const to var. This is mean that webpack convert my files to es5.

How can I tell webpack to convert to es6? (leave the const as it is and/or use import keyword for example)

app.js

import {test} from './some';

const x = 1;

console.log('test', test);
console.log('this should be const in the bundle, not var. ', x);

And the bundle is:

"use strict";
__webpack_require__.r(__webpack_exports__);
/* harmony import */ var _some__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! ./some */ "./some.js");

var x = 1;
console.log('test', _some__WEBPACK_IMPORTED_MODULE_0__["test"]);
console.log('this should be const in the bundle, not var. ', x);

/***/ }),

my webpack config:

const path = require('path');

module.exports = () => [
  {
    mode: 'development',
    entry: path.resolve(__dirname, './app.js'),
    output: {
      path: path.resolve(__dirname, './dist')
    },
    devtool: 'source-map',
    target: 'node',
    module: {
      rules: [
        {
          test: /\.m?js$/,
          exclude: /(node_modules|bower_components)/,
          use: {
            loader: 'babel-loader',
            options: {
              presets: ['@babel/preset-env']
            }
          }
        }
      ]
    }
  }
];

Upvotes: 0

Views: 1660

Answers (1)

Pretseli
Pretseli

Reputation: 1347

You are using the @babel/preset-env without any options. That will transform the code to ES5 and the documentation says it's not really recommended to use it this way. The whole point of the "env" preset is that you give a target platform and it will automatically apply the transformations, which are needed for that platform. Passing "targets.node"-option value true or "current" will transform the code for the currently used node-version. Using the preset with this option has the additional advantage, that upgrading node.js will not require any changes in Babel configuration and less code will be transformed, if the new node.js supports more of the ES features used.

Support for ECMAScript modules in node.js is still experimental, but you can disable module transformation by passing false to "modules"-option.

options: {
    presets: [[
        '@babel/preset-env',
        {
            targets: {
                node: "current"
            },
            modules: false
        }
    ]]
}

Upvotes: 2

Related Questions