Javascript 如何在客户端使用 node.js 模块系统
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4944863/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
how to use node.js module system on the clientside
提问by Nicolas Mommaerts
I would like to use the CommonJS module system in a clientside javascript application. I chose nodejs as implementation but can't find any tutorial or docs on how to use nodejs clientside, ie without using node application.js
我想在客户端 javascript 应用程序中使用 CommonJS 模块系统。我选择 nodejs 作为实现,但找不到任何关于如何使用 nodejs 客户端的教程或文档,即不使用node application.js
I included node.js like this in my html page:
我在我的 html 页面中包含了这样的 node.js:
<script type="text/javascript" src="node.js"></script>
Note that I didn't make nodejs on my local machine, I'm on Windows anyway (I'm aware of the Cygwin option).
When I want to use the require
function in my own javascript it says it's undefined.
请注意,我没有在本地机器上创建 nodejs,无论如何我都在 Windows 上(我知道 Cygwin 选项)。当我想require
在我自己的 javascript 中使用该函数时,它说它是未定义的。
var logger = require('./logger');
My question is, is it possible to use nodejs like this?
我的问题是,是否可以像这样使用 nodejs?
采纳答案by Raynos
Node.js
is a serverside application where you run javascript on the server. What you want to do is use the require
function on the client.
Node.js
是一个服务器端应用程序,您可以在其中在服务器上运行 javascript。您要做的是require
在客户端上使用该功能。
Your best bet is to just write the require
method yourself or use any of the other implementations that use a different syntax like requireJS.
最好的require
办法是自己编写方法或使用任何其他使用不同语法(如requireJS )的实现。
Having done a bit of extra research it seems that no-one has written a require module using the commonJS syntax for the client. I will end up writing my own in the near future, I recommend you do the same.
经过一些额外的研究,似乎没有人使用 commonJS 语法为客户端编写了一个 require 模块。我最终会在不久的将来自己写,我建议你也这样做。
[Edit]
[编辑]
One important side effect is that the require
function is synchronous and thus loading large blocks of javascript will block the browser completely. This is almost always an unwanted side-effect. You need to know what you're doing if you're going to do this. The requireJS syntax is set up so that it can be done asynchronously.
一个重要的副作用是该require
函数是同步的,因此加载大块 javascript 将完全阻止浏览器。这几乎总是一种不需要的副作用。如果你要这样做,你需要知道你在做什么。设置了 requireJS 语法,以便它可以异步完成。
回答by Marcello Bastea-Forte
SubStack on github has a module called node-browserify.
github 上的 SubStack 有一个名为node-browserify 的模块。
It will compress and bundle your modules and deliver it as a single js file, but you use it just like Node.js (example from module readme):
它将压缩和捆绑您的模块并将其作为单个 js 文件交付,但您可以像使用 Node.js 一样使用它(模块自述文件中的示例):
<html>
<head>
<script type="text/javascript" src="/browserify.js"></script>
<script type="text/javascript">
var foo = require('./foo');
window.onload = function () {
document.getElementById('result').innerHTML = foo(100);
};
</script>
</head>
<body>
foo = <span style='font-family: monospace' id="result"></span>
</body>
</html>
From the module description:
从模块描述:
Browserify
Browser-side require() for your node modules and npm packages**
Browserify bundles everything ahead-of-time at the mount point you specify. None of this ajaxy module loading business.
More features:
- recursively bundle dependencies of npm modules
- uses es5-shim for browsers that suck
- filters for {min,ugl}ification
- coffee script works too!
浏览器化
用于 node 模块和 npm 包的浏览器端 require()**
Browserify 在您指定的挂载点提前捆绑所有内容。没有这个ajaxy模块加载业务。
更多功能:
- 递归捆绑 npm 模块的依赖项
- 对糟糕的浏览器使用 es5-shim
- {min,ugl} 化过滤器
- 咖啡脚本也可以!
回答by Katie
Browserifymagically lets you do that.
Browserify神奇地让你做到这一点。
回答by AlienKevin
Webpack
网络包
I would recommend Webpackwhich automates node module loading, dependencies, minification, and much more.
我会推荐Webpack,它可以自动加载节点模块、依赖项、缩小等等。
Installation
安装
To use node modules in your project, first install node.json your machine. The package management system NPMshould be installed along the way. If you have already installed node.js, update Node.js and NPM to the latest version.
要在你的项目中使用节点模块,首先在你的机器上安装node.js。包管理系统NPM应该沿途安装。如果您已经安装了 node.js,请将 Node.js 和 NPM 更新到最新版本。
Usage
用法
Initialization
初始化
Open your project in your code editor and inititialize npm by typing npm init -y
to the command line. Next, install webpack locally by typing npm install webpack webpack-cli --save-dev
. (--save-dev
means these dependencies are added to the devDependencies
section of your package.json
file which are not required for production)
在您的代码编辑器中打开您的项目并通过npm init -y
在命令行中键入来初始化 npm 。接下来,通过键入在本地安装 webpack npm install webpack webpack-cli --save-dev
。(--save-dev
意味着这些依赖项被添加到devDependencies
您的package.json
文件中不需要生产的部分)
Reorder Folder Structure
重新排序文件夹结构
Follow the tree structure below to reconstruct your project folder:
按照下面的树结构重建您的项目文件夹:
yourProjectName
|- package.json
|- /dist
|- index.html
|- /src
|- index.js
Create a dist
folder to hold all distribution files and move index.html
to that folder. Next, create a src
folder for all source files and move your js file to that folder. You should use the exact same file and folder namesas appeared in the tree structure. (these are the default of Webpack but you can configure them later by editing webpack.config.js
)
创建一个dist
文件夹来保存所有分发文件并移动index.html
到该文件夹。接下来,src
为所有源文件创建一个文件夹,并将您的 js 文件移动到该文件夹中。您应该使用与树结构中出现的完全相同的文件和文件夹名称。(这些是 Webpack 的默认设置,但您可以稍后通过编辑对其进行配置webpack.config.js
)
Refactor dependencies
重构依赖
Remove all <script>
importations in index.html
and add <script src="main.js"></script>
before the </body>
tag. To import other node modules, add import statementsat the beginning of your index.js
file. For example, if you want to import lodash
, just type import _ from 'lodash';
and proceed to use the _
in your index.js
file.
删除所有<script>
导入index.html
并添加<script src="main.js"></script>
在</body>
标签之前。要导入其他节点模块,请在文件开头添加import 语句index.js
。例如,如果您想导入lodash
,只需键入import _ from 'lodash';
并继续_
在您的index.js
文件中使用 。
NOTE: Don't forget to first install the node package first before importing it in JS. To install lodash
locally, type npm install lodash
. Lodash will be automatically saved to your production dependencies in package.json
注意:不要忘记先安装 node 包,然后再将其导入 JS。要lodash
在本地安装,请键入npm install lodash
. Lodash 将自动保存到您的生产依赖项中package.json
Run Webpack
运行 Webpack
Finally, run webpack by typing npx webpack
in your command line. You should see main.js
generated in the dist
folder for you by Webpack.
最后,通过npx webpack
在命令行中键入来运行 webpack 。您应该会main.js
在dist
Webpack 为您生成的文件夹中看到。
Additional resources
其他资源
The above guide provides only the most basic way to use Webpack. To explore more useful use cases, go to the official tutorialof Webpack. It provides extremely comprehensive tutorials on topics such as asset management, output management, guides for development and production, etc.
以上指南仅提供了最基本的 Webpack 使用方法。要探索更多有用的用例,请转到Webpack的官方教程。它提供了关于资产管理、输出管理、开发和生产指南等主题的极其全面的教程。
Reference
参考
回答by Mariusz Nowak
If you'd like to write code for browser with same style modules as you do for Node.js, try Webmake. Take a look also at simple prototype of application build that way: SoundCloud Playlist Manager
如果您想使用与 Node.js 相同的样式模块为浏览器编写代码,请尝试Webmake。还看一下以这种方式构建的应用程序的简单原型:SoundCloud Playlist Manager
回答by Alex Nolasco
The accepted answer is correct when it comes to RequireJS. But, fast-forward to 2020 and we now have ES modulespretty much on every browser except IE <= 11.
当涉及到 RequireJS 时,接受的答案是正确的。但是,快进到 2020 年,除了 IE <= 11 之外,我们现在几乎在每个浏览器上都有ES 模块。
So, to answer your question "how to use node.js module system on the clientside". You could leverage ES modules already, e.g.
所以,回答你的问题“如何在客户端使用 node.js 模块系统”。您已经可以利用 ES 模块,例如
<!DOCTYPE html>
<head>
<meta charset="utf-8" />
<title>Hello 2020</title>
<script
src="https://code.jquery.com/jquery-3.5.1.min.js"
integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0="
crossorigin="anonymous"
></script>
<!-- load the app as a module, also use defer to execute last -->
<script defer type="module" src="./app.js"></script>
</head>
<html lang="en">
<body>
<div id="app">
<h1>Demo</h1>
</div>
</body>
</html>
app.js
应用程序.js
import { hello } from './utils.js'
(function () {
$('#app').fadeOut(2000, function(e) {
console.log(hello('world'));
});
})();
util.js
实用程序
function hello(text) {
return `$hello {text}`;
}
export { hello };
Now let's assume you want to use an npm package in your browser (assuming this package can run on both browser and node). In that case, you may want to check out Snowpack.
现在让我们假设您想在浏览器中使用 npm 包(假设这个包可以在浏览器和节点上运行)。在这种情况下,您可能需要查看 Snowpack。
Snowpack 2.0 is a build system designed for this new era of web development. Snowpack removes the bundler from your dev environment, leveraging native ES Module (ESM) support to serve built files directly to the browser
Snowpack 2.0 是为这个 Web 开发新时代而设计的构建系统。Snowpack 从您的开发环境中删除打包程序,利用原生 ES 模块 (ESM) 支持将构建的文件直接提供给浏览器
In other words, you can use npm packages thus allowing you to use the "node module system" in your client application.
换句话说,您可以使用 npm 包,从而允许您在客户端应用程序中使用“节点模块系统”。
回答by Volker Weckbach
There is a good require node.js-like library for client side. It's called wrapup. Check it out kamicane/wrapup
客户端有一个很好的类似 node.js 的库。这叫做总结。检查一下kamicane/总结