gpt4 book ai didi

reactjs - React、ES6 使用 Browserify、babel 和 gulp 编译,导入组件时出现问题

转载 作者:行者123 更新时间:2023-12-03 14:15:11 24 4
gpt4 key购买 nike

我正在使用 ES6、Gulp 和 Browserify,这是我设置环境的第一步。

这是我的 browserify task :

gulp.task('client', cb => {
return browserify({
entries: paths.publicEntries,
extensions: ['.jsx'],
debug: true
})
.transform('babelify', {
presets: ['es2015', 'react']
})
.bundle()
.pipe(source(paths.bundle))
.pipe(gulp.dest(paths.bundleDest));
});

这是五月主脚本 index.jsx

'use strict';

import React from 'react';
import ReactDOM from 'react-dom';
import TestPage from './components/test';

(() => {
ReactDOM.render(
<TestPage/>,
document.getElementById('mainContainer')
);
})();

这是我创建的组件 test.jsx

'use strict';

import React from 'react';

class TestPage extends React.Component {
render()
{
return <h1> Hello World! </h1>
}
}

export default TestPage;

对我来说一切看起来都不错,但是在 index.jsx 中使用 import 语句会出现奇怪的行为(我不完全知道问题出在哪里)。

为了确定哪些有效,哪些无效,我将组件的导入替换为实际代码,如下所示:

'use strict';

import React from 'react';
import ReactDOM from 'react-dom';
//import TestPage from './components/test';

class TestPage extends React.Component {
render()
{
return <h1> Hello World! </h1>
}
}

(() => {
ReactDOM.render(
<TestPage/>,
document.getElementById('mainContainer')
);
})();

enter image description here

这里一切正常,但如果我使用标准 import 语句,我什么也得不到:

enter image description here

注意:

  • ./component/test.jsx./index.jsx 已正确加载。
  • 运行 gulp 时没有出现任何错误。
  • reactreact-dom 模块正在运行。
  • 我尝试使用另一条路径访问我的组件./public/js/component/test.jsx,但在运行我的 gulp 任务时出现错误错误:找不到模块'。/public/js/components/test' from '/Users/myuser/project/public/js' 这意味着它正在找到正确的模块,就像现在一样,但不在浏览器中。
  • 尝试使用和不使用 .jsx 扩展名,情况相同。

如果有人想更深入地了解这里的存储库: https://github.com/nramirez/gulp_browserify_es6_babel_react

为了正确导入我的组件,我缺少什么?

最佳答案

您正在 gulpfile.babel.js 中为您的应用创建多个入口点(基本上,您正在创建两个包)。

const paths = {
src: './src',
publicSrc: './public/js',
dest: './app',
bundle: 'bundle.js',
bundleDest: './app/public/js',
publicEntries: [
'./public/js/index',
'./public/js/components/test' <--- Remove this line.
]
};

关于reactjs - React、ES6 使用 Browserify、babel 和 gulp 编译,导入组件时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34848085/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com