使用新创建的React + Typescript Webpack应用设置“ npm start”?

时间:2019-12-08 14:08:58

标签: reactjs typescript webpack

我需要在Webpack的初始设置方面提供一些帮助,以通过热重载为我的应用程序提供服务。我遵循this guide来使用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/

1 个答案:

答案 0 :(得分:0)

欢迎来到社区。 关于webpack的设置,请尝试将其添加到package.json

"scripts": {
"start": "webpack-dev-server --mode development --open --hot"
},

当您执行npm start时,启动将从该脚本开始,并将应用程序作为webpack运行。而且--hot将确保热重载为真,即在您对应用程序进行的任何更改时自动重载。 将应用程序推入生产环境时,请务必将模式更改为生产环境,以免在生产环境中收到所有错误和警告。希望能帮助到你 !!