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

标签 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')

/***/ })

是不是配置有问题?

最佳答案

这其实不是因为 babel,而是因为 webpack。它需要一个名为 devtool 的选项决定是否应该eval代码或使用某种源映射。

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

// webpack.config.js (excerpt)
module.exports = {
    // ...
    devtool: 'inline-source-map'
    // ...
};
inline-source-map省略 eval 以支持包内的 - 良好 - 内联的源映射。但是不要将它用于生产;-)
devtool 有几个选项各有优缺点。有关该主题的更多信息,请参阅 official webpack documentation .

关于Webpack Babel-loader 使用 eval() 转译代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50358773/

相关文章:

javascript - 如何在 Vue-CLI 3 项目中全局声明 jQuery?

jquery-file-upload - 如何在webpack中使用blueimp-file-upload?

javascript - 意外的 token 导入(React JS 和 Babel)

javascript - Webpack 2.3.3 - 类型错误 : $export is not a function

webpack - 如何使用 webpack 观看特定文件?

reactjs - 在 Gatsby/React 中将文件作为字符串(或源 Assets )导入

webpack - 组合多个 webpack block

javascript - 使用 Webpack 将 ES6 转译为单独的文件

webpack - 模块构建失败(来自 ./node_modules/babel-loader/lib/index.js): TypeError: Cannot read property 'bindings' of null

webpack - babel vs babel-core vs babel-loader vs babel-preset-2015 vs babel-preset-react vs babel-polyfill