1

我似乎让 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)

入口.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'));

测试.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 应该设置正确。所以也许我只是在一个我没有看到的初学者陷阱中? - 我将不胜感激任何帮助。

4

2 回答 2

2

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

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

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

于 2018-07-09T22:25:39.180 回答
1

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

browserify({
                extensions: ['.ts', '.tsx', '.js', '.jsx']
          }).add(...).bundle(...)
于 2019-07-20T22:44:57.330 回答