【问题标题】:browserify bundle doesn't handle importing files via relative pathbrowserify bundle 不处理通过相对路径导入文件
【发布时间】:2016-12-04 06:10:55
【问题描述】:

我正在使用 browserify 和 babel 来编译和捆绑我的 react 应用程序。来自client/ 的文件被捆绑到一个文件static/bundle.js 中。但我使用了似乎处理不正确的相对导入。

这是我的文件结构

client/
    components/
        main.js
    App.js
static/
    bundle.js
gulpfile.js

这是我的 gulpfile 和有问题的导入

// client/App.js

import React, { Component } from 'react';
import { render } from 'react-dom';
import App from './components/main.js';


render(
  <App />,
  document.getElementById('root'),
);


// gulpfile.js

var gulp = require('gulp');
var browserify = require('browserify');
var babelify = require('babelify');
var source = require('vinyl-source-stream');

gulp.task('build', function() {
  browserify({
    entries: 'client/App.js',
    extensions: ['.js'],
    debug: true
  })
    .transform(babelify, {presets: ['es2015', 'react']})
    .bundle()
    .pipe(source('bundle.js'))
    .pipe(gulp.dest('static'));
});

问题出在import App from './components/main.js';这一行。

当我查看static/bundle.js 时,有一行var _main = require('./components/main.js');,这没有意义,因为相对于bundle.js,没有./components/main.js。这是相对于client/App.js 定义的。

browserify 不处理这些事情吗?还有其他我应该使用的工具,还是我做的其他事情不正确?

【问题讨论】:

    标签: javascript reactjs ecmascript-6 babeljs


    【解决方案1】:

    您必须将 paths 添加到您的 browserify 选项中。如果你不添加,browserify 不知道在哪里寻找你的模块。

    module.exports = function(grunt){
      grunt.initConfig({
    
        browserify: {
          options:{
            browserifyOptions: {
    
              // ...
              paths: [
                './node_modules',
                './client'
              ]
    
            }
          },
          // ...
        },
        // ...
      });
    }
    

    在他们解决之前这是一个issue

    【讨论】:

    • 我使用“模块”这个词可能会产生误导。我只想从我的另一个文件中导入,不一定是带有index.js 的目录(更新的标题没有“模块”一词)。在我看来,这改变了答案。
    • 不一定,options里有没有路径?
    猜你喜欢
    • 1970-01-01
    • 2022-10-24
    • 2010-10-24
    • 2021-12-20
    • 1970-01-01
    • 2012-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多