错误:无法使用browserify + babelify查找模块

时间:2017-08-13 08:11:02

标签: gulp browserify babel babelify

我似乎让React和ReactDOM与Browserify完美配合,但是当我尝试在同一目录中导入/需要我自己的模块时,显然找不到它!

错误

events.js:160
      throw er; // Unhandled 'error' event
      ^

Error: Cannot find module './test' from '/var/www/resources/assets/js'
    at /var/www/node_modules/browser-resolve/node_modules/resolve/lib/async.js:55:21
    at load (/var/www/node_modules/browser-resolve/node_modules/resolve/lib/async.js:69:43)
    at onex (/var/www/node_modules/browser-resolve/node_modules/resolve/lib/async.js:92:31)
    at /var/www/node_modules/browser-resolve/node_modules/resolve/lib/async.js:22:47
    at FSReqWrap.oncomplete (fs.js:123:15)

entry.jsx

import ReactDOM from 'react-dom';
const browser = require('./test');    // <<< Can't find the file in the same dir?

ReactDOM.render(browser, document.getelementbyid('store-page'));

test.jsx

import React from 'react';

export default class test extends React.Component {
    render() {
        return <h1>Hello, React!</h1>
    }
}

gulpfile.js

gulp.task('babel', function() {

    let b = browserify({                                            // Get API access to Browserify for transformations.
        entries: config.babel.input,                                // Our entry.js file.
        debug: isDebug                                              // Used for sourcemaps.
    });

    b.transform('babelify');                                        // Convert our Babel code to JavaScript.

    return b.bundle()                                               // Bundle all our converneted JavaScript into one source.
        .pipe(source('bundle.js'))                                  // Tells the filename of the stream we want to write to.
        .pipe(buffer())                                             // Bundle our converted JavaScript code into a stream for pipeline.
        .pipe(gulpif(isDebug, sourcemaps.init({loadMaps: true})))   // Generate a sourcemap file for better analysis and debugging.
            .pipe(gulpif(isProduction, uglify()))                   // Convert our code into minification for better performance and bandwidth.
            .on('error', gutil.log)                                 // Routes any error messages to the console and continues our task manager like normal.
        .pipe(gulpif(isDebug, sourcemaps.write('./')))              // Write a sourcemap file in the same destination.
        .pipe(gulp.dest(config.babel.output));                      // Write the compiled JavaScript to the destination for our browser.
});

从我收集的内容中,我应该正确设置gulpfile.js。所以也许我只是在一个我没看到的初学者陷阱? - 我将不胜感激任何帮助。

2 个答案:

答案 0 :(得分:0)

一种解决方案是指定文件扩展名。

const browser = require('./test.jsx');

我自己尝试解决同一问题时发现了这个问题。希望能够允许babel / browserify在不指定的情况下找到jsx文件。

答案 1 :(得分:0)

我知道这是一个令人难以置信的晚答案。但是我找到了解决方案。如果您使用的是Browserify api,请尝试将扩展名设置为可以导入的文件扩展名:

browserify({
                extensions: ['.ts', '.tsx', '.js', '.jsx']
          }).add(...).bundle(...)