在Webpack中使用TypeScript的更高效的方法是什么?

时间:2018-07-10 07:34:12

标签: typescript webpack

在Typescript文档中,有an example使用ts-loader插件来提取TypeScript文件,如下所示:

module.exports = {
    entry: "./src/index.tsx",
    output: {
        filename: "bundle.js",
        path: __dirname + "/dist"
    },

    // Enable sourcemaps for debugging webpack's output.
    devtool: "source-map",

    resolve: {
        // Add '.ts' and '.tsx' as resolvable extensions.
        extensions: [".ts", ".tsx", ".js", ".json"]
    },

    module: {
        rules: [
            // All files with a '.ts' or '.tsx' extension will be handled by 'awesome-typescript-loader'.
            { test: /\.tsx?$/, loader: "awesome-typescript-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"
    }
};

其他选择是像使用tsc({script}编译器)一样package.json script

"build": "tsc && webpack"

在Webpack中使用TypeScript的哪种方法更高效?

1 个答案:

答案 0 :(得分:1)

我建议使用ts-loader,因为它可以进行更细粒度的优化。您可以使用cache-loaderhard-source-webpack-plugin缓存中间结果,并使用happy-pack在多个线程中运行它。 Webpack的webpack 5 milestone

中还包括一些优化

PS。大约awesome-typescript-loader-github page很好地涵盖了它与ts-loader之间的所有差异。它不支持HappyPack,但另一方面具有缓存和babel中更好的集成。我建议尝试这两个选项,然后选择较快运行的一个,基本上是在配置中更改了几行。