我有一个文件,我们将调用 file1.ts
:
export { default as function1 } from 'function1.ts';
export { default as function2 } from 'function2.ts';
我使用 Webpack 和 Babel 编译它:webpack.config.js
const path = require("path");
module.exports = {
target: "web",
mode: "production",
entry: "./src/index.ts",
output: {
path: path.resolve(__dirname, "./lib/cjs"),
filename: "index.js",
libraryTarget: "commonjs2",
},
resolve: {
extensions: [".ts", ".tsx", ".js"],
},
module: {
rules: [
{
test: /\.(ts|tsx)$/,
exclude: /(node_modules)/,
loader: "babel-loader",
options: {
presets: [
"@babel/preset-react",
"@babel/preset-typescript",
[
"@babel/preset-env",
{
targets: ["last 2 versions"],
},
],
],
plugins: ["babel-plugin-styled-components"],
},
},
],
},
};
我将此发布到 npm。现在我想将它导入我们将调用的 file2.ts
:import { function1 } from 'package';
但是,function1 不存在,因为如果我存在,例如 import a from 'package';
, a
是 undefined
.为了解决这个问题,我决定创建另一个文件,我们将调用
file0.js
执行以下操作:module.exports = require('./file1.js');
如果我在控制台记录要求,它将是一个带有 function1
的模块对象和 function2
然而,正如我所料,module.exports = require('./file1.js');
未定义...所以我尝试了以下方法:var test = require('./file1.js');
module.exports = { ...test };
module.exports = require('./file1.js');
没有。 最佳答案
webpack 不是为支持发射 ES 模块而设计的。它的 ES 模块支持适用于在内部使用 ES 模块但发出不同格式的应用程序。我建议使用 Rollup相反,它具有完整的原生 ES 模块支持,但如果您仍然需要它也可以支持具有相同配置的 CJS。
关于javascript - 如何 module.exports 另一个模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62625334/