让 Webpack 不捆绑文件

IT技术 javascript node.js reactjs typescript webpack
2021-04-18 17:55:21

所以现在我正在使用一个原型,我们使用 webpack(用于构建 .tsx 文件和复制 .html 文件)和 webpack-dev-server 之间的组合进行开发服务。你可以假设我们也使用 React 和 ReactDOM 作为几个库依赖项。我们当前的构建输出是以下结构:

dist
    -favicon.ico
    -index.html
    -main.js
    -main.js.map // for source-mapping between tsx / js files

这会将所有module(包括库依赖项放入大捆绑文件中)。我希望最终结果如下所示:

dist
    -favicon.ico
    -index.html
    -appName.js
    -appName.min.js
    -react.js
    -react.min.js
    -reactDOM.js
    -reactDOM.min.js

我在 index.html 和 .tsx 文件中的 import 语句中引用了每个库。所以我的问题是......我如何从 webpack 生成这个巨大的捆绑 .js 文件到单独的 .js 文件(包括库,而不必单独指定每个文件)?**奖励:我知道如何做 prod/dev 环境标志,那么我如何只缩小这些单个文件(同样不捆绑它们)?

当前的 webpack.config:

var webpack = require("webpack"); // Assigning node package of webpack dependency to var for later utilization
var path = require("path"); // // Assigning node package of path dependency to var for later utilization

module.exports = {
    entry:  [
                "./wwwroot/app/appName.tsx", // Starting point of linking/compiling Typescript and dependencies, will need to add separate entry points in case of not deving SPA
                "./wwwroot/index.html", // Starting point of including HTML and dependencies, will need to add separate entry points in case of not deving SPA
                "./wwwroot/favicon.ico" // Input location for favicon
            ],
    output: {
        path: "./dist/", // Where we want to host files in local file directory structure
        publicPath: "/", // Where we want files to appear in hosting (eventual resolution to: https://localhost:4444/)
        filename: "appName.js" // What we want end compiled app JS file to be called
    },

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

    devServer: {
        contentBase: './dist', // Copy and serve files from dist folder
        port: 4444, // Host on localhost port 4444
        // https: true, // Enable self-signed https/ssl cert debugging
        colors: true // Enable color-coding for debugging (VS Code does not currently emit colors, so none will be present there)
    },

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

    module: {
        loaders: [
            // This loader copies the index.html file & favicon.ico to the output directory.
            {
                test: /\.(html|ico)$/,
                loader: 'file?name=[name].[ext]'
            },
            // All files with a '.ts' or '.tsx' extension will be handled by 'ts-loader'.
            {
                test: /\.tsx?$/,
                loaders: ["ts-loader"]
            }
        ],

        preLoaders: [
            // All output '.js' files will have any sourcemaps re-processed by 'source-map-loader'.
            {
                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",
    //     "redux": "Redux"
    // }
};
3个回答

output设置更改名称驱动,例如

    entry: {
        dash: 'app/dash.ts',
        home: 'app/home.ts',
    },
    output: {
        path: './public',
        filename: 'build/[name].js',
        sourceMapFilename: 'build/[name].js.map'
    },
经过一些研究,最接近最终解决方案的结果。我在上面的解释中添加了我最终解决方案的评论。使用您的方法的一个缺点是,当指定不同类型的文件作为文件加载器的入口点(即 favicon.ico、index.html)时,它们也将与 .js 及其原始文件一起输出。
2021-06-13 17:55:21
知道这在项目中节省了多少时间吗?如果 webpack 基本上什么都不做,只是将文件从输入复制到输出,那么在添加转译和其他插件/加载器转换之前是否有很多开销?
2021-06-14 17:55:21

要扩展@basarat 的答案,您可以使用glob节点标准库中包来构建“条目”配置:

const glob = require("glob");

module.exports = [
  {
    target: "node",
    entry: glob.sync("./src/**/*.test.{ts,tsx}").reduce((acc, file) => {
      acc[file.replace(/^\.\/src\//, "")] = file;
      return acc;
    }, {}),
    output: {
      filename: "[name].js",
      chunkFilename: "[name]-[id].js",
      path: __dirname + "/dist"
    },
    //...
  }
];

这将构建与其源同名的文件,将.ts替换.tsx.js.

OPs 的答案复制出了问题

最终找到了一个适合我需求的解决方案,尽管再次以 webpack-y 方式需要一些额外的配置。仍然希望让它更有活力,但会在稍后的时间点完善它。我正在寻找的解决方案是能够“分块”通用module,但我将其表示为文件名,给出了 webpack 中提供的“入口”点。我不介意合并一些文件,这是有意义的,但希望整个文件处于组件级别,因为项目不是 SPA(单页应用程序)。

额外的代码最终是:

plugins: [
    new webpack.optimize.CommonsChunkPlugin({ // This plugin is for extracting and created "chunks" (extracted parts of the code that are common and aren't page specific)
        // One of these instances of plugins needs to be specified for EACH chunk file output desired
        filename: "common.js", // Filename for this particular set of chunks to be stored
        name: "common", // Entry point name given for where to pull all of the chunks
        minChunks: 3 // Minimum number of chunks to be created
    })
]

我还必须通过变量名参数化入口点(例如见下文),以便我可以将 react、react-dom 和 redux module分配给 common.js 文件。

entry:  {
    main:    "./wwwroot/app/appName.tsx", // Starting point of linking/compiling Typescript and dependencies, will need to add separate entry points in case of not deving SPA
    index:   "./wwwroot/index.html", // Starting point of including HTML and dependencies, will need to add separate entry points in case of not deving SPA
    favicon: "./wwwroot/favicon.ico", // Input location for favicon
    common:  [ "react", "react-dom", "redux" ] // All of the "chunks" to extract and place in common file for faster loading of common libraries between pages
},
您是否估计不捆绑(在分析时间?)与捆绑相比节省了多少时间?
2021-06-12 17:55:21