React,Typescript和Webpack将bundle.js添加到页面的问题



当我构建项目时,它构建得很好,并创建bundle.js文件,但当导航到http://localhost:8080/我在控制台上收到警告:

Loading failed for the <script> with source “http://localhost:8080/dist/bundle.js”.

我真的对此感到困惑,因为似乎一切都在正确地构建和开始。

我浏览了其中的每一页:1 2 3 4,并尝试了它们在上面显示的内容,但没有任何变化。

我的webpack.config.js文件:

"use strict"
const path = require('path');
module.exports = {
entry: './App.tsx',
output: {
filename: "bundle.js",
path: path.resolve(__dirname, 'dist')
},
devServer: {
publicPath: "/",
contentBase: "./public",
hot: true
},
resolve: {
extensions: ['.ts', '.tsx', '.js']
},
devtool: "inline-source-map",
module: {
rules: [{
test: /.(ts|tsx)$/,
use: 'ts-loader',
exclude: /node_modules/
},
{
test: /.css$/,
use: [
'style-loader',
'css-loader'
]
}]
}
};

tsconfig.json:

{
"compilerOptions": {
"outDir": "./dist/",
"sourceMap": true,
"noImplicitAny": true,
"module": "commonjs",
"target": "es5",
"jsx": "react",
"allowJs": true
},
"include": [
"App.tsx"
]
}

软件包.json

{
"name": "project",
"version": "1.0.0",
"private": true,
"main": "App.tsx",
"devDependencies": {
"@babel/core": "^7.2.2",
"@babel/preset-env": "^7.3.1",
"@babel/preset-react": "^7.0.0",
"@types/react": "^16.8.1",
"@types/react-dom": "^16.0.11",
"babel": "^6.23.0",
"babel-loader": "^8.0.5",
"css-loader": "^2.1.0",
"react-hot-loader": "^4.6.5",
"source-map-loader": "^0.2.4",
"style-loader": "^0.23.1",
"ts-loader": "^5.3.3",
"tslint": "^5.12.1",
"tslint-react": "^3.6.0",
"typescript": "^3.3.1",
"webpack": "^4.29.1",
"webpack-cli": "^3.2.2",
"webpack-dev-server": "^3.1.14"
},
"dependencies": {
"awesome-typescript-loader": "^5.2.1",
"react": "^16.7.0",
"react-dom": "^16.7.0",
"react-scripts": "2.1.3"
},
"scripts": {
"start": "webpack-dev-server --hot --inline",
"build": "webpack"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": [
">0.2%",
"not dead",
"not ie <= 11",
"not op_mini all"
]
}

App.tsx就这么简单,直到我可以使用这个测试:

import * as React from "react";
import * as ReactDOM from "react-dom";
import "./App.css";
export interface Props {}
export interface State {}
class App extends React.Component<Props, State> {
public render(): JSX.Element {
return (
<div className="test">
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById("root"));

作为参考,如果我遗漏了一些非常简单的东西,我的文件结构如下:

project
|- package.json
|- package-lock.json
|- tsconfig.json
|- tslint.json
|- webpack.config.js
|- App.tsx
|- App.css
|- /dist
|- bundle.js
|- /public
|- index.html
|- /node_modules

在将其切换到带有React的Typescript之前(我只将React与webpack一起使用,然后决定使用Typescript、React和webpack),它将div添加到根div中,没有问题,我希望它也能这样做,但现在它只加载了只有<div id="root"></div><script src="../dist/bundle.js"></script>index.html页面

好吧,原来这只是一个简单的问题。我想index.html需要和bundle.js在同一个目录中。一旦我把index.html移到dist中,它就可以正常工作了。

最新更新