简体   繁体   English

如何将 Node 添加到前端?

[英]How do you add Node to the frontend?

I have been coding with a React frontend and a Node/Express backend.我一直在使用 React 前端和 Node/Express 后端进行编码。 But sometimes, I only need some plain Javascript without React, but still want the benefit of NPM and other Node modules.但有时,我只需要一些没有 React 的普通 Javascript,但仍然想要 NPM 和其他 Node 模块的好处。 What is a way to do this?有什么方法可以做到这一点?

You'll need a module bundler of some kind.您将需要某种模块捆绑器。 There are many options including Webpack , Browserify, Gulp, and Parcel.有很多选项,包括Webpack 、Browserify、Gulp 和 Parcel。

For Webpack, for example, from their example docs, the process could be:例如,对于 Webpack,从他们的示例文档中,该过程可能是:

  • Install webpack with npm install webpack and install webpack-cli安装 webpack 和npm install webpack并安装webpack-cli

  • Install a module you want to use on the frontend, eg lodash安装一个你想在前端使用的模块,例如 lodash

  • In src/index.js , import lodash: import _ from 'lodash';src/index.js中,导入 lodash: import _ from 'lodash'; and use it as needed.并根据需要使用它。 (You can also import other modules from NPM or from other places in your source code) (您也可以从 NPM 或源代码中的其他位置导入其他模块)

  • Set up webpack.config.js if you need custom build configuration settings如果需要自定义构建配置设置,请设置webpack.config.js

  • Run webpack to build the project: npx webpack .运行 webpack 来构建项目: npx webpack A single bundled JavaScript file will be created which contains all your source code and the imported Lodash's source code.将创建一个捆绑的 JavaScript 文件,其中包含所有源代码导入的 Lodash 源代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM