我有两个文件导入到 main.js 中。我想将所需对象或整个模块的所有代码导入到 dist.js 中 - 主要是将 nodejs 文件中提到的所有需要模块捆绑到一个包中。有人知道一个简单的方法吗?我正在考虑使用 webpack,但是有支持吗?在此处打开打字稿支持的文件
file1.js
function myfunctionhere() {}
module.exports = {
myfunctionhere
}
file2.js
function myfunctionsecondhere() {}
function myfunctionfunctionhere() {}
module.exports = {
myfunctionsecondhere,
myfunctionfunctionhere
}
main.js
const f1 = require("./file1.js");
const { myfunctionsecondhere } = require("./file2.js");
myfunctionhere()
myfunctionsecondhere()
捆绑后的文件应该是这样的:
dist.js
function myfunctionhere() {}
const f1 = { myfunctionhere }
function myfunctionsecondhere() {}
myfunctionhere()
myfunctionsecondhere()
我正在考虑使用 webpack,但是有支持吗?在此处打开打字稿支持的文件。我有什么选择?
将 Node.js 模块捆绑到单个文件中,特别是在浏览器等环境中使用或用于分发时,可以通过各种工具和捆绑器来实现。 Webpack 确实是此任务中最受欢迎的选项之一,它提供了广泛的功能和插件来处理不同类型的文件,包括 JavaScript 和 TypeScript。以下是使用 Webpack 的场景的基本设置,以及您可能考虑的其他工具的简要概述。
要使用 Webpack 将 Node.js 文件捆绑到单个
dist.js
文件中,请按照以下步骤操作:
npm init -y
npm install --save-dev webpack webpack-cli
在项目根目录中创建一个名为
webpack.config.js
的文件:
const path = require('path');
module.exports = {
entry: './main.js', // Your entry file
output: {
path: path.resolve(__dirname, 'dist'), // Output directory
filename: 'dist.js' // Output file
},
target: 'node', // Target environment
mode: 'production', // Could be 'development' for debugging purposes
};
package.json
以包含构建脚本:"scripts": {
"build": "webpack"
}
npm run build
这将在您的
dist.js
目录中生成一个 dist
文件,将条目文件中的代码及其依赖项捆绑在一起。
如果您使用 TypeScript,则需要将 TypeScript 支持添加到 Webpack 配置中:
npm install --save-dev typescript ts-loader
在您的
webpack.config.js
中添加模块规则:
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/,
},
],
},
resolve: {
extensions: ['.tsx', '.ts', '.js'],
},
tsconfig.json
文件:运行
npx tsc --init
并根据您的项目需要调整生成的 tsconfig.json
。
通过执行以下步骤,您可以将 Node.js 或 TypeScript 文件捆绑到单个文件中,以便在本身不支持模块的环境中分发或使用。每个工具都有其优点,因此请根据项目的具体需求和复杂性进行选择。