Why is it necessary to install Browserify twice to bundle

对着背影说爱祢 提交于 2019-12-24 01:21:47

问题


I created a new project

I npm install -g browserify

I tested using the cmdline, browserify app.js > bundle.js. Cool.

I want to minify so I npm install uglifyify --save-dev

I tested using the cmdline, browserify -g uglifyify app.js > bundle.js. Great.

Now I want to do this with code, but I get Error: Cannot find module 'browserify'

This is my code, basically to replace the cmdline

var browserify = require('browserify')
var fs = require('fs')

var bundler = browserify('./app.js')

bundler.transform({
    global: true
}, 'uglifyify')

bundler.bundle()
    .pipe(fs.createWriteStream('./bundle.js'))

It seems I would need to again install browserify locally to this project?


回答1:


Installing an npm module like browserify allows you to use browserify as a command on the command line. To use the module within your project's code, you must install the module as a dependency. In other words, yes, is must be installed locally within the project's ./node_modules folder and referenced in the package.json file.

From the npm documentation:

  • Local install (default): puts stuff in ./node_modules of the current package root.
  • Global install (with -g): puts stuff in /usr/local or wherever node is installed.
  • Install it locally if you're going to require() it.
  • Install it globally if you're going to run it on the command line.
  • If you need both, then install it in both places, or use npm link.



回答2:


As said in the other answer, one way to solve this is that you can install browserify locally instead of globally, like: npm install --save browserify uglifyfy. Then you can add a script in package.json:

...
"scripts": {
  "build": "browserify app.js > bundle.js",
   ...
},
...

Now, npm run-script build will know how to find local browserify, which is going to be in your node_modules/ directory. And your require('browserify') will work, since browserify is now local.


Another way you could solve this is NODE_PATH env variable. Set this variable in your bashrc or equivalent like this:

export NODE_PATH=$NODE_PATH:$HOME/.nvm/versions/node/v4.2.6/lib/node_modules

Adjust the path to wherever your global node_modules are. Then you can require() whatever you installed with -g flag in your code.

However this is suboptimal, as it can lead to errors and misunderstandings. But if it's for some quick-and-dirty scripts, it can help.



来源:https://stackoverflow.com/questions/35992104/why-is-it-necessary-to-install-browserify-twice-to-bundle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!