Webpack Babel-loader使用eval()转换代码

时间:2018-05-15 20:34:42

标签: webpack babel-loader

我遇到了Webpack和Babel的问题。我正在尝试将我的JavaScript代码转换为捆绑文件。这是文件结构和片段:

文件结构:

- src
| file.js
package.json
webpack.config.js

的package.json:

{
  "name": "babel-webpack-starter",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "build": "webpack --mode development"
  },
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "babel-core": "^6.26.3",
    "babel-loader": "^7.1.4",
    "babel-preset-env": "^1.7.0",
    "webpack": "^4.8.3",
    "webpack-cli": "^2.1.3",
    "webpack-dev-server": "^3.1.4"
  }
}

webpack.config.js:

const path = require('path');

module.exports = {
    entry: {
        app: './src/file.js'
    },
    output: {
        path: path.resolve(__dirname, 'build'),
        filename: 'app.bundle.js'
    },
    module: {
        rules: [
            {
                test: /\.js?$/,
                exclude: /node_modules/,
                use: [
                    {
                        loader: 'babel-loader',
                        options: {
                            presets: ['env']
                        }
                    }
                ]
            }
        ]
    }
}

当我输入webpack --mode development时,它会在目录app.bundle.js内成功创建文件build

enter image description here

但是,它似乎没有正常工作,因为在build/app.bundle.js的末尾,我正在寻找src/file.js的代码,我有以下内容:

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

"use strict";
eval("\n\nvar fun = function fun() {\n  return console.log('Hello World');\n};\n\n//# sourceURL=webpack:///./src/file.js?");

/***/ })

这很奇怪,我不应该只是这样做吗?

/***/ (function(module, exports, __webpack_require__) {

"use strict";
let fun = () => console.log('Hello World')

/***/ })

配置有问题吗?

2 个答案:

答案 0 :(得分:10)

这实际上不是因为babel,而是因为webpack。它需要一个名为devtool的选项来决定它是eval代码还是使用某种源映射。

您可能正在寻找以下内容:

// webpack.config.js (excerpt)
module.exports = {
    // ...
    devtool: 'inline-source-map'
    // ...
};

inline-source-map省略了eval,支持捆绑内部的 - 内联源代码映射。但是,不要将它用于生产; - )

devtool有几个选项都有其优点和缺点。有关该主题的更多信息,请参阅official webpack documentation

答案 1 :(得分:2)

经过无数个小时的研究,我终于找到了解决方案,需要使用的预设是babel-preset-env不是env

const path = require('path');

module.exports = {
    entry: {
        app: './src/file.js'
    },
    output: {
        path: path.resolve(__dirname, 'build'),
        filename: 'app.bundle.js'
    },
    module: {
        rules: [
            {
                test: /\.js?$/,
                exclude: /node_modules/,
                use: [
                    {
                        loader: 'babel-loader',
                        options: {
                            presets: ['babel-preset-env'] // <-- here
                        }
                    }
                ]
            }
        ]
    }
}