webpack + babel 配置构建空输出文件

Webpack + babel configuration builds empty output file

我有以下配置:

package.json

{
  "name": "webpacksetup",
  "version": "1.0.0",
  "description": "",
  "main": "webpack.config.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "@babel/cli": "^7.12.10",
    "@babel/core": "^7.12.10",
    "@babel/preset-env": "^7.12.11",
    "babel-loader": "^8.2.2",
    "webpack": "^5.11.0",
    "webpack-cli": "^4.3.0"
  }
}

webpack.config.js

const path = require('path');

module.exports = {
  entry: { index: path.resolve(__dirname, "src", "index.js") },
  output: {
    path: path.resolve(__dirname, "dist")
  },
  module: {
    rules: [
      {
        test: /\.js$/,
        exclude: /node_modules/,
        use: [{
                        loader: "babel-loader",
                        options: {
                                presets: ["@babel/preset-env"]
                        }
                }]
      }
    ]
  },
};

src/index.js(只有箭头函数我想转译成ES5并保存在dist/目录)

const MyFunction = () => {
        return [1, 2, 3];
}

当我 运行 "npx webpack" 然后生成空 dist/index.js 文件(而不是具有转译功能的文件)。当我从 CLI 运行 babel 时,我得到了预期的结果:

npx babel src/index.js --presets=@babel/preset-env
"use strict";

var MyFunction = function MyFunction() {
  return [1, 2, 3];
};

知道我做错了什么吗?

谢谢

Webpack 捆绑了 CommonJS 和 ESM 模块,而不是文件,因此像您拥有的文件这样的文件正在模块内创建一个 MyFunction 作用域。由于实际使用 MyFunction 的模块中没有任何内容,我猜测 Webpack 正在将其作为死代码删除。

由于您的意图是将其用作全局函数,因此您应该明确地将其设为全局函数,例如

window.MyFunction = () => {
    return [1, 2, 3];
};

哪个 Webpack 不会删除。