我尝试使用 require.ensure 为 Facility.js 创建 block
import React, { Component } from 'react';
import { render } from 'react-dom';
class Facility extends Component {
constructor(...args) {
super(...args);
this.state = {
....
};
}
render() {
return (
<div>
....
</div>
);
}
}
export default Facility;
//Tried module.exports = Facility;
NonPatientSer.js
var Facility;
require.ensure([], function(require) { Facility = require('./Facility'); }, 'facility');
开发 我可以在我的源代码中看到 facility.bundle.js 但对它的调用返回 undefined 和这个错误
Warning: React.createElement: type should not be null, undefined, boolean, or number. It should be a string (for DOM elements) or a ReactClass (for composite components). Check the render method of
NonPatientSer
和
Uncaught Invariant Violation: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. Check the render method of
NonPatientSer
.
生产(运行构建)
Not allowed to load local resource: file:///C:/Users/.../facility.bundle.js
Webpack 配置
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: __dirname + '/',
chunkFilename: '[name].bundle.js'
},
最佳答案
首先,您需要修复 webpack.config 中的 publicPath 属性。你应该使用:
publicPath: '/dist/'
而不是绝对路径。
其次,如果您对导出模块使用 es6 语法:
export default Facility;
你应该这样写你的导入代码:
require.ensure([], function(require) {
Facility = require('./Facility').default;
ReactDOM.render(<Facility/>, document.getElementById('app'));
}, 'facility');
或者只是使用 commonjs 语法:
module.exports = Facility;
然后
require.ensure([], function(require) {
Facility = require('./Facility');
ReactDOM.render(<Facility/>, document.getElementById('app'));
}, 'facility');
另请参阅:http://www.2ality.com/2015/12/babel-commonjs.html
更新: 您可以在入口 js 文件中设置 publicPath。例如:
entry.js
__webpack_public_path__ = '/publicPathToChunk/';
var chunk;
require.ensure([], function(require) {
chunk = require('./chunk');
}, 'chunk');
此外,您还可以使用下一个技巧:
var bundleSrc = document.querySelector('[src*="bundle"]').getAttribute("src");
__webpack_public_path__ = bundleSrc.substr(0, bundleSrc.lastIndexOf("/") + 1);
关于javascript - 如何修复 require.ensure 错误 Webpack、Babel6、React?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36394787/