Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
571 views
in Technique[技术] by (71.8m points)

babeljs - Webpack + babel configuration builds empty output file

I have the following configuration:

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 (only arrow function I want transpile into ES5 and save in dist/ directory)

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

When I run "npx webpack" then empty dist/index.js file is generated (instead of file with transpiled function). When I run babel from CLI then I get the expected result:

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

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

Any idea what I'm doing wrong?

Thank you


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Webpack bundles CommonJS and ESM modules, not files, so a file like the one you have is creating a MyFunction scoped within a module. Since there is nothing in the module that actually uses MyFunction, I would guess that Webpack is deleting it as dead code.

Since your intent is to use this as a global function, you should be explicitly making it global, e.g.

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

which Webpack would not delete.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...