我需要一些关于 webpack 初始设置的帮助,以便为我的应用程序提供热重载。我已经按照本指南使用 Typescript 设置 React+Webpack,但我想知道如何设置它,以便我可以调用"npm start
"并让它编译和托管应用程序,并热重载。
我的webpack.config.js
如下所示:
module.exports = {
mode: "production",
// Enable sourcemaps for debugging webpack's output.
devtool: "source-map",
resolve: {
// Add '.ts' and '.tsx' as resolvable extensions.
extensions: [".ts", ".tsx"]
},
module: {
rules: [
{
test: /.ts(x?)$/,
exclude: /node_modules/,
use: [
{
loader: "ts-loader"
}
]
},
// All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
{
enforce: "pre",
test: /.js$/,
loader: "source-map-loader"
}
]
},
// When importing a module whose path matches one of the following, just
// assume a corresponding global variable exists and use that instead.
// This is important because it allows us to avoid bundling all of our
// dependencies, which allows browsers to cache those libraries between builds.
externals: {
"react": "React",
"react-dom": "ReactDOM"
}
};
我的package.json
看起来像这样:
{
"name": "client",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "test"
},
"author": "DMW",
"license": "ISC",
"devDependencies": {
"@types/react": "^16.9.15",
"@types/react-dom": "^16.9.4",
"source-map-loader": "^0.2.4",
"ts-loader": "^6.2.1",
"typescript": "^3.7.3",
"webpack": "^4.41.2",
"webpack-cli": "^3.3.10",
"webpack-dev-server": "^3.9.0"
},
"dependencies": {
"react": "^16.12.0",
"react-dom": "^16.12.0"
},
"keywords": []
}
如果有人可以将我链接到某些东西以使它正常工作,我将不胜感激。我对找到的搜索结果有点害怕。
编辑:我最终使用了npx create-react-app app --template typescript
,详见此处:https://create-react-app.dev/docs/adding-typescript/
欢迎来到社区。 关于 webpack 的设置,请尝试将其添加到您的包中.json
"scripts": {
"start": "webpack-dev-server --mode development --open --hot"
},
当你执行 npm start 时,start 将从此脚本中获取,并将应用程序作为 webpack 运行。此外,--hot 将确保热重载为真,即在您对应用程序所做的任何更改时自动重新加载。 在将应用推送到生产环境时,请务必将模式更改为生产环境,以免在生产环境中收到所有错误和警告。希望有帮助!!