webpack 配置:
node_modules 中 js/jsx 加载器配置:
{
test: /\.(js|jsx)?$/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env', '@babel/preset-react'],
plugins: [
"@babel/plugin-transform-arrow-functions",
"@babel/plugin-proposal-class-properties",
]
}
},
include: [
resolve("./node_modules/npm-package"),
],
exclude: [
resolve("./src"),
resolve("./node_modules/npm-package/node_modules"),
],
}
node_modules 中 css 加载器配置:
{
test:/\.css$/,
use: ['style-loader', 'css-loader', 'less-loader'],
include: [
resolve("./node_modules/npm-package"),
],
// exclude: /node_modules/,
}
npm 组件引用:
import React, { PureComponent, createElement } from "react";
/**
* 异步加载组件
* @param load 组件加载函数,load 函数会返回一个 Promise,在文件加载完成时 resolve
* @returns {AsyncComponent} 返回一个高阶组件用于封装需要异步加载的组件
*/
function getAsyncComponent(load) {
return class AsyncComponent extends PureComponent {
componentDidMount() {
// 在高阶组件 DidMount 时才去执行网络加载步骤
load().then(({default: component}) => {
// 代码加载成功,获取到了代码导出的值,调用 setState通知高阶组件重新渲染子组件
// console.log('component', component);
this.setState({
component,
})
});
}
render() {
const {component} = this.state || {};
// component 是 React.Component 类型,需要通过React.createElement生产一个组件实例
return component ? createElement(component) : null;
}
}
}
<Route path="/test-path" component={getAsyncComponent(
() => import(/* webpackChunkName: '/testPath' */'npm-package/src/test-compo')
)} />