我正在将 React + Typescript 与 Webpack 一起使用,并且我正在尝试在实际需要时加载我的一些 React 组件。
问题是,当通过延迟加载请求块时,我收到以下错误:
未捕获的错误:加载块 1 失败。(错误:http://localhost:58988/1.chunk.js)在 HTMLScriptElement.onScriptComplete (bootstrap:114)
这个块生成成功并且没有任何错误,只是路径错误 -http://localhost:58988/1.chunk.js
应该是http://localhost:58988/dist/1.chunk.js
我也尝试使用最新React.lazy
的延迟加载react组件,但我遇到了同样的问题。那么,有没有办法告诉编译器如何解析这些文件路径?
这是一些代码:
我的组件.tsx
import * as React from "react";
import * as ES5Promise from "promise";
export class MyComponent extends React.Component<{}, {}> {
constructor(props) {
super(props);
}
private readonly onLoadModuleClickHandler = (): void => {
import("./Button").then((module) => {
console.log(module);
});
}
render() {
return (
<div>
<input type="button" value="Load another module" onClick={this.onLoadModuleClickHandler}/>
</div>
);
}
}
配置文件
{
"compilerOptions": {
"moduleResolution": "node",
"noImplicitAny": false,
"noEmitOnError": true,
"module": "esnext",
"removeComments": false,
"sourceMap": false,
"target": "es5",
"jsx": "react",
"noEmit": true,
"importHelpers": true,
"lib": ["dom", "es5", "es2015.promise"]
},
"exclude": [
"node_modules",
"wwwroot"
]
}
webpack.config.js
module.exports = {
entry: {
"app": "./src/App.tsx"
},
output: {
path: path.resolve(__dirname, 'wwwroot/dist'),
filename: "[name].bundle.js",
chunkFilename: "[name].chunk.js"
},
module: {
rules: [
{
test: /\.(ts|tsx)?$/,
use: "awesome-typescript-loader",
exclude: /node_modules/
},
{
test: /\.(css|less)?$/,
use: [{
loader: "style-loader"
}, {
loader: "css-loader?modules&localIdentName=[local]--[hash:base64:5]"
}, {
loader: "less-loader"
}]
},
]
},
resolve: {
extensions: [".js", ".jsx", ".ts", ".tsx", ".css", ".less"]
}
};