1

我有模块化的javascript应用程序,我需要在一个文件“global-libs.js”中包含js框架,使用webpack的每个文件都可以访问这些依赖项。其他 js 文件将仅使用这些依赖项,但不会成为最终包的一部分。我正在结合 Webpack 使用 Gulp 来完成这些任务。

这是 webpack 的任务,并将我的 jsx 转换为 js,其中应该只有我的代码,而不是外部库

gulp.task('js',['jsx'], function () {
    /**This dependency is external, its not part of the bundle */
    return gulp.src(config.paths.workDir + config.paths.jsPath + '/**/*.js')
        .pipe(webpack({
            externals: {
                "react": "React"
            }
        }))
        .pipe(rename('onlyCustomJs.js'))
        .pipe(gulpif(args.production, uglify()))
        .pipe(gulp.dest(config.paths.portlets.newNotePortlet + config.paths.jsPath))
});

这个任务应该只使用外部库创建文件,并且依赖 React 应该可以在每个 js webpack 文件中使用 require 来访问。

gulp.task('global', function(){
    /**This will be accessible globally*/
    return gulp.src(config.paths.srcDir + config.paths.jsPath + '/global-libs.js')
    .pipe(webpack({
        output: {
            libraryTarget: "var",
            library: "React"
        }
    }))
    .pipe(rename('global-libs.js'))
    .pipe(gulp.dest(config.paths.portlets.evremTheme + config.paths.jsPath))
});

该文件使用全局反应依赖。但它告诉我 React 在 var HelloMessage = React.. 处未定义。

/** @jsx React.DOM */
var React = require('react');

var HelloMessage = React.createClass({
  render: function() {
    return <div>Hello {this.props.name}</div>;
  }
});

React.renderComponent(HelloMessage({name: "Hello world"}), document.getElementById('example'));

这是 global-libs.js 文件

var React = require('react');
var jQuery = require('jquery');

谢谢!

4

1 回答 1

0

也许这不是最好的解决方案,但我通过这些变化解决了。

//这些依赖项将捆绑在一个 global-libs.js 文件中,并且可以通过 require() 从任何地方访问。

module.exports = React = require('react');
module.exports = jQuery = require('jquery');

Webpack 只合并这两个文件,通过 module.exports 发布

gulp.task('global', function(){
  /**This will be accessible globally*/
  return gulp.src(config.paths.srcDir + config.paths.jsPath + '/global-libs.js')
    .pipe(webpack())
    .pipe(rename('global-libs.js'))
    .pipe(gulp.dest(config.paths.destDir + config.paths.jsPath))
});

我捆绑我的 conde 的 gulp 任务是这样的。仅指定的外部依赖项不会成为捆绑包的一部分。

 gulp.task('js',['jsx'], function () {
        /**This dependency is external, its not part of the bundle */
        return gulp.src(config.paths.workDir + config.paths.jsPath + '/**/*.js')
            .pipe(webpack({
                externals: {
                    "react": "React",
                    "jquery": "jQuery"
                }
            }))
            .pipe(rename('bundle.js'))
            .pipe(gulpif(args.production, uglify()))
            .pipe(gulp.dest(config.paths.destDir + config.paths.jsPath))
    });

结果我可以像这样导入依赖项。

/** @jsx React.DOM */
var React = require('react');
var jQuery = require('jquery');

var HelloMessage = React.createClass({
  render: function() {
    return <div>Hello {this.props.name}</div>;
  }
});

React.renderComponent(HelloMessage({name: "Hello world"}), jQuery('#example')[0]);
于 2014-10-19T13:25:37.003 回答