我想将我的react组件服务器端转换为一个bundle.min.js
文件。我遇到的问题是该文件不解析import语句。
这是我想要传输的文件( client / component.js )
import React from 'react';
import ReactDom from 'react-dom';
import App from './components/app';
ReactDom.render(<App />, document.getElementById('app'));
结果就是这个( bundle.min.js )
'use strict';
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _reactDom = require('react-dom');
var _reactDom2 = _interopRequireDefault(_reactDom);
var _app = require('./components/app');
var _app2 = _interopRequireDefault(_app);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
_reactDom2.default.render(_react2.default.createElement(_app2.default, null), document.getElementById('app'));
但这不是我想要的。
我需要删除所有import语句并替换为我需要的实际文件。就我而言,我需要
// builds the components and clientside
gulp.task('buildComponentsClient', () =>
gulp.src(['./client/*.js'])
.pipe(include()).on('error', console.log)
.pipe(babel({ presets: ['es2015', 'react']}))
.pipe(concat('bundle.js'))
// .pipe(uglify({mangle: false}))
.pipe(rename('bundle.min.js'))
.pipe(gulp.dest('./public'))
);
如何使用这些简约反应元素文件中指定的所有依赖项创建浏览器友好文件?
答案 0 :(得分:2)
根据我的理解,你不能使用browserify
加上babelify
。以下是我的一项任务:
import gulp from 'gulp';
import glob from 'glob';
import browserify from 'browserify';
import babelify from 'babelify';
import rename from 'gulp-rename';
import source from 'vinyl-source-stream';
import es from 'event-stream';
import uglify from 'gulp-uglify';
import buffer from 'vinyl-buffer';
const path = './client/';
const files = '*.js';
const bundles = [path + files]; // I use an array to be able to bundle
// multiple paths within the same task
gulp.task('bundle', () => {
let bundleAll = bundles.map(bundle);
return Promise.all(bundleAll); // Task ends when all bundles are done
});
// Bundle files found in bundlePath, returns a Promise resolved
// when all files have been processed
function bundle(bundlePath) {
return new Promise((resolve, reject) => {
glob(bundlePath, (err, files) => { // Create glob from path
var tasks = files.map(file => { // loop through each file
return browserify(file) // pass it to browserify
.transform(babelify, ["es2015", "react"]) // using babelify (browserify + babel)
.bundle() // ..profit!
.on('error', err => {
console.error('err', err.toString());
reject(err);
})
.pipe(source(file)) // this is required for browserify output to be use as a gulp stream
.pipe(buffer()) // needed by gulp-uglify
.pipe(uglify())
.pipe(rename({ 'bundle.min.js' }))
.pipe(gulp.dest('./public'));
});
es.merge(tasks).on('end', resolve); // When all files have been processed, resolve the promise we returned
});
});
}