简体   繁体   English

Browserify 找不到本地模块

[英]Browserify can't find local module

I have same issue but with local component.我有同样的问题,但有本地组件。

That's my tree:那是我的树:

app
|
 - assets
  |
   - js
    |
     - app.jsx
    |
     - MainComponent.jsx 

But when I run command:但是当我运行命令时:

macpro:app user$ browserify assets/js/app.jsx > tesapp.js

It response error :它响应错误:

Error: Cannot find module 'MainComponent' from '/Users/user/WebstormProjects/gowithme/app/assets/js'错误:无法从“/Users/user/WebstormProjects/gowithme/app/assets/js”中找到模块“MainComponent”

That is code of app.jsx file :那是 app.jsx 文件的代码:

var React = require('react');
var ReactDOM =  require('react-dom');
var  MainComponent  = require('MainComponent');
console.log("Test",MainComponent);

It happens because you are using .jsx extension.发生这种情况是因为您使用的是.jsx扩展名。 By default browserify cannot recognize unknown extension.默认情况下,browserify 无法识别未知扩展名。 Add browserifyOptions to you grunt config, it might help:browserifyOptions添加到您的 grunt 配置中,它可能会有所帮助:

options: {
    transform: [['babelify', {presets: ['es2015', 'react']}]],
    browserifyOptions: {
        debug: true,
        extensions: ['.jsx']
    }
}

Also I suggest to omit usage of .jsx .另外我建议省略.jsx使用。 No .jsx extension? 没有 .jsx 扩展名?

You need to give the relative path when you're loading a local module (ie a .js file of your own) with require :当您使用require加载本地模块(即您自己的.js文件)时,您需要提供相对路径:

var React = require('react');
var ReactDOM =  require('react-dom');
var  MainComponent  = require('./MainComponent'); //added ./ so now the path is relative
console.log("Test",MainComponent);

When using an absolute path (like require('fs') or require('react') ) node will try to load native modules (like fs , path etc) or modules inside node_modules .当使用绝对路径(如require('fs')require('react') )时,节点将尝试加载本地模块(如fspath等)或node_modules内的模块。

https://nodejs.org/api/modules.html#modules_modules https://nodejs.org/api/modules.html#modules_modules

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

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