Reputation: 7144
So 3 days ago I hit weird problem with bundling simple function with babel, typescript and webpack.
Whole "not working" example is available at https://codesandbox.io/s/zen-wright-y3vql. You just need download, npm/yarn install
, npm/yarn run build
and node test-run.js
.
I have just few simple files.
export const sum = (a: number, b: number) => a + b;
{
"name": "babel-test",
"version": "1.0.0",
"main": "dist/index.js",
"scripts": {
"dev": "webpack",
"build": "NODE_ENV=production webpack"
},
"dependencies": {},
"devDependencies": {
"@babel/core": "^7.10.4",
"@babel/preset-env": "^7.10.4",
"@babel/preset-typescript": "^7.10.4",
"@types/node": "^14.0.23",
"@types/webpack": "^4.41.21",
"babel-loader": "^8.1.0",
"ts-node": "^8.10.2",
"typescript": "^3.9.6",
"webpack": "^4.43.0",
"webpack-cli": "^3.3.12"
}
}
{
"presets": [
"@babel/preset-env",
"@babel/preset-typescript"
]
}
{
"compilerOptions": {
"module": "commonjs",
"jsx": "preserve",
"esModuleInterop": true,
"sourceMap": true,
"allowJs": true,
"lib": [
"es6",
"dom"
],
"rootDir": "src",
"moduleResolution": "node"
}
}
import path from "path";
import webpack from "webpack";
const isProduction = process.env.NODE_ENV === "production";
const isDevelopment = !isProduction;
const config: webpack.Configuration = {
mode: isProduction ? "production" : "development",
entry: "./src/index.ts",
watch: isDevelopment,
output: {
filename: "index.js",
path: path.resolve(__dirname, "dist/"),
},
module: {
rules: [
{
test: /\.(js|ts)$/,
exclude: [/node_modules/],
loader: "babel-loader",
},
],
}
};
export default config;
const sum = require("./dist/index.js");
console.log(sum);
sum(1, 2);
And, after build it with webpack
or npm run build
and run with node test-run.js
I have this error:
/Users/sigo/Downloads/hife9/test-run.js:4
sum(1, 2);
^
TypeError: sum is not a function
at Object.<anonymous> (/Users/sigo/Downloads/hife9/test-run.js:4:1)
at Module._compile (internal/modules/cjs/loader.js:1201:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1221:10)
at Module.load (internal/modules/cjs/loader.js:1050:32)
at Function.Module._load (internal/modules/cjs/loader.js:938:14)
at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
at internal/main/run_main_module.js:17:47
I've tried tricks with core-js
and transform runtime/regenerator
things without result.
Upvotes: 1
Views: 544
Reputation: 27257
You have sum
as a named export, but you importing it as if it were the default export.
Read about the difference on MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export.
It should be imported like so:
const { sum } = require("./dist/index.js");
console.log(sum);
sum(1, 2);
Here is an updated CodeSandbox to demonstrate: https://codesandbox.io/s/serene-gould-1xnw7
(I made various other changes to your CodeSandbox, as it did not work as-is.)
Upvotes: 1