I trying to use require.ensure to create a chunk for Facility.js
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');
Dev I can see facility.bundle.js in my sources but the call for it returns undefined and this errors
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
and
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
.
Production (run build)
Not allowed to load local resource: file:///C:/Users/.../facility.bundle.js
Webpack config
output: {
path: path.join(__dirname, 'dist'),
filename: 'bundle.js',
publicPath: __dirname + '/',
chunkFilename: '[name].bundle.js'
},
First, you need to fix publicPath property in your webpack.config. You should use:
publicPath: '/dist/'
instead absolute path.
At second, if you use es6 syntax for export module:
export default Facility;
you should write your import code like this:
require.ensure([], function(require) {
Facility = require('./Facility').default;
ReactDOM.render(<Facility/>, document.getElementById('app'));
}, 'facility');
Or just to use commonjs syntax:
module.exports = Facility;
and then
require.ensure([], function(require) {
Facility = require('./Facility');
ReactDOM.render(<Facility/>, document.getElementById('app'));
}, 'facility');
See also: http://www.2ality.com/2015/12/babel-commonjs.html
Update: You can set publicPath in your entry js file. For example:
entry.js
__webpack_public_path__ = '/publicPathToChunk/';
var chunk;
require.ensure([], function(require) {
chunk = require('./chunk');
}, 'chunk');
Also, you can use next trick:
var bundleSrc = document.querySelector('[src*="bundle"]').getAttribute("src");
__webpack_public_path__ = bundleSrc.substr(0, bundleSrc.lastIndexOf("/") + 1);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.