【问题标题】:ES6 not getting compiled. I am using Babel with WebpackES6 没有被编译。我正在使用带有 Webpack 的 Babel
【发布时间】:2019-09-06 11:07:24
【问题描述】:

我正在尝试将 babel 与 webpack 一起使用,以便将我的 ES6 代码转换为 vanilla javascript。我没有收到任何错误,但我不认为我的 ES6 正在转换为 vanilla Javascript。我正在为 webpack 和 babel 使用以下包-

"@babel/core": "^7.5.5",
"@babel/preset-env": "^7.5.5",
"babel-loader": "^8.0.6",
"webpack": "^4.39.3",
"webpack-cli": "^3.3.7"

这是我的 webpack.config.js 文件 -:

const path = require('path');

const config = {
 entry: './src/index.js',
 output: {
     path: path.resolve(__dirname, 'build'),
     filename: 'bundle.js'
 },
 mode: 'development',
 module: {
     rules: [
         {
             test: '/\.js$/',
             loader: 'babel-loader',
             exclude: '/node_modules/'
         }
     ]
 }
}

module.exports = config;

在我的 .babelrc 文件中我也写过 -:

{
    "presets": ["@babel/preset-env"]
}

bundle.js 仍然有相同的代码 -:

/*! no static exports found */
/***/ (function(module, exports, __webpack_require__) {

eval("const sum = __webpack_require__(/*! ./sum */ \"./src/sum.js\");\r\n\r\nconst total = sum(10, 4);\r\n\r\nlet array = [1,2,3];\r\n\r\nArray.from(array).forEach(($item) => {\r\n console.log($item);\r\n})\r\n\r\nconsole.log(total);\n\n//# sourceURL=webpack:///./src/index.js?");

/***/ }),

/***/ "./src/sum.js":
/*!********************!*\
  !*** ./src/sum.js ***!
  \********************/
/*! no static exports found */
/***/ (function(module, exports) {

eval("const sum = (a, b) => a + b;\r\n\r\nmodule.exports = sum;\n\n//# sourceURL=webpack:///./src/sum.js?");

/***/ })

此代码仍然具有 const 和箭头函数。 所以没有错误,但仍然没有编译代码。

【问题讨论】:

    标签: javascript webpack babeljs


    【解决方案1】:

    您的.babelrc 中缺少targets 选项:

    {
      "targets": "last 1 version, IE >= 11"
    }
    

    或者(现在这是推荐的方式),将其引入项目的package.json

    "browserslist": [
        "last 1 version",
        "IE >= 11"
    ]
    

    【讨论】:

      猜你喜欢
      • 2019-10-18
      • 2021-09-17
      • 1970-01-01
      • 2017-03-13
      • 2019-04-14
      • 2019-11-09
      • 2016-07-28
      • 2018-03-11
      • 1970-01-01
      相关资源
      最近更新 更多