Cannot find module 'jquery' when using bro

2019-06-04 07:03发布

I am trying to use browserify for a small web application, what I would like to achieve is pretty basic: I would like to be able to require('jquery') in my JS code instead of having the dependency linked with a <script> tag in the HTML code.

So, I have this in the first line of my JS file called main.js:

require('jquery');

Then, I start browserify to produce bundle.js:

browserify main.js -o bundle.js

Output:

Error: Cannot find module 'jquery' from /home/matias/dev/app/js

However, it seems jquery is properly installed:

npm -g list | grep jquery

returns jquery@2.1.4.

Any idea what I am doing wrong ?

EDIT: installing modules 'locally' (without -g option) seems to work with browserify - is it the right way to do ? I would prefer to have it using globally installed modules.

1条回答
男人必须洒脱
2楼-- · 2019-06-04 07:25

It is highly recommended to install modules locally. This way, each project depends on the specific versions it needs, and there is no risk of regressions from backwards-incompatible changes. When you upgrade a global module, anything that depends on it could potentially break.

Whether you are using browserify or not, npm dependencies should be fixed to a specific version (likely, the latest version at the time of authoring). They should only be upgraded (past a major version) when you have the time to test and make sure nothing breaks, using a tool such as npm-check-updates.

All that said, you can run npm link jquery from inside your project directory to make the local dependencies (in node_modules) symlink to the globally installed jquery. This is helpful when you are developing the dependency module, but it is not suitable for normal use.

In your situation, use local dependencies.

查看更多
登录 后发表回答