我正在将 React + Typescript 与 Webpack 一起使用,并且我正在尝试在实际需要时加载我的一些反应组件。
问题是,当通过延迟加载请求块时,我收到以下错误:
未捕获的错误:加载块 1 失败。 (错误:http://localhost:58988⁄1.chunk.js)在 HTMLScriptElement.onScriptComplete (引导程序:114)
这个chunk生成成功,没有任何错误,只是路径不对 http://localhost:58988/1.chunk.js
应该是 http://localhost:58988/dist/1.chunk.js
我也尝试过使用最新的 React.lazy
来延迟加载反应组件,但我遇到了同样的问题。那么,有没有办法告诉编译器如何解析这些文件路径?
这是一些代码:
我的组件.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>
);
}
}
tsconfig.json
{
"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"]
}
};
原文由 Martin Shishkov 发布,翻译遵循 CC BY-SA 4.0 许可协议
发生这种情况是因为
output.publicPath
默认情况下是/
。只需更新
output.publicPath
指向您想要的位置 =>/dist/
。