gpt4 book ai didi

node.js - 如何在客户端代码中使用 Node 模块?

转载 作者:搜寻专家 更新时间:2023-10-31 23:54:16 25 4
gpt4 key购买 nike

我在我的 nodejs 应用程序中安装了 ReactJs 模块,因此 React 出现在 node_modules 目录中。但是我不能在客户端javascript中使用它,因为没有引用。

那么添加此类引用的最佳方式是什么?(当然我可以手动复制react.js脚本到scripts文件夹,然后手动添加引用,但是会导致代码重复,而且看起来很丑)

最佳答案

Browserify是您正在寻找的工具。它采用 Node 模块并包装它们,因此您可以 require()它们在客户端 JavaScript 代码中。

示例来自 Browserify's readme

Whip up a file, main.js with some require()s in it. You can use relative paths like './foo.js' and '../lib/bar.js' or module paths like 'gamma' that will search node_modules/ using node's module lookup algorithm.

var foo = require('./foo.js');
var bar = require('../lib/bar.js');
var gamma = require('gamma');

var elem = document.getElementById('result');
var x = foo(100) + bar('baz');
elem.textContent = gamma(x);

Export functionality by assigning onto module.exports or exports:

module.exports = function (n) { return n * 111 }

Now just use the browserify command to build a bundle starting at main.js:

$ browserify main.js > bundle.js

All of the modules that main.js needs are included in the bundle.js from a recursive walk of the require() graph using required.

To use this bundle, just toss a <script src="bundle.js"></script> into your html!

关于node.js - 如何在客户端代码中使用 Node 模块?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28803050/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com