Webpack将整个rxjs添加到捆绑中

时间:2019-05-07 09:51:11

标签: typescript webpack rxjs

我仅在一次导入的地方使用rxjs@6.5.1webpack@4.30.0):

import {debounceTime, distinctUntilChanged, map} from "rxjs/operators";
import {fromEvent, Observable} from "rxjs";

但是在捆绑包webpack中添加了整个rxjs:

enter image description here

这是我的tsconfig

{
  "compilerOptions": {
    "module": "commonjs",
    "target": "es5",
    "sourceMap": true,
    "allowJs": true,
    "typeRoots": [
      "node_modules/@types"
    ]
  },
  "exclude": [
    "node_modules"
  ]
}

和我的webpack.config

const webpack = require('webpack');
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
var CleanWebpackPlugin = require('clean-webpack-plugin');
var GlobEntries = require('webpack-glob-entries');
var ManifestPlugin = require('webpack-manifest-plugin');
var CopyWebpackPlugin = require('copy-webpack-plugin');
const BundleAnalyzerPlugin = require('webpack-bundle-analyzer').BundleAnalyzerPlugin;
var HtmlWebpackPlugin = require('html-webpack-plugin');

var entriesRest = {
    "style": "./assets/css/style.scss",
};

var entries = GlobEntries('./assets/js/entries/**/*.ts');

const outputDir = 'public';

const plugins = [
    new HtmlWebpackPlugin(),
    new webpack.ProgressPlugin(),
    new webpack.ProvidePlugin({
        $: "jquery",
        jQuery: "jquery",
        "window.jQuery": "jquery",
        popper: 'popper',
        "window.popper": 'popper',
        Popper: 'popper',
        "window.Popper": 'popper',
    }),
    new MiniCssExtractPlugin({
        filename: '../css/style-[contenthash].css',
    }),
    new CleanWebpackPlugin(),
    new ManifestPlugin({
        // publicPath:'../../',
        fileName: '../../' + outputDir + '/manifest.json',
        generate: (seed, files) => {
            const entrypoints = new Set()
            files.forEach(
                (file) => ((file.chunk || {})._groups || []).forEach(
                    (group) => entrypoints.add(group)
                )
            )
            const entries = [...entrypoints]
            const entryArrayManifest = entries.reduce((acc, entry) => {
                const name = (entry.options || {}).name
                    || (entry.runtimeChunk || {}).name
                const files = [].concat(
                    ...(entry.chunks || []).map((chunk) => chunk.files)
                ).filter(Boolean)
                return name ? {...acc, [name]: files} : acc
            }, seed)
            return entryArrayManifest
        }
    }),
    new CopyWebpackPlugin([
        {from: 'node_modules/ckeditor', to: 'ckeditor'},
        {from: 'assets/img', to: '../img'},
        {from: 'assets/index.php', to: '../index.php'},
        {from: 'assets/cron-20min.php', to: '../cron-20min.php'},
        {from: 'assets/js/ads.js', to: '../js/ads.js'},
        {from: 'assets/.htaccess', to: '../[name].[ext]'},
    ]),
];

module.exports = (argv, env) => {
    return {
        plugins: [
            ...plugins,
            env.mode === 'development' ? new BundleAnalyzerPlugin() : [],
        ],
        entry: Object.assign(entriesRest, entries),
        optimization: {
            splitChunks: {
                chunks: "all"
            },
        },
        devtool: env.mode === 'development' ? 'eval' : '',
        output: {
            path: path.resolve(__dirname, outputDir + "/js/"),
            filename: '[name]-[chunkhash].js',//-[hash:6]
        },
        module: {
            rules: [
                {
                    test: /\.css$/i,
                    use: ['style-loader', 'css-loader']
                },
                {
                    test: /\.ts$/,
                    loader: 'ts-loader',
                    options: {
                        transpileOnly: true
                    }
                },
                {
                    test: /\.scss$/i,
                    include: [
                        path.resolve(__dirname, "assets/css/style.scss"),
                    ],
                    use: [
                        {
                            loader: MiniCssExtractPlugin.loader,
                            options: {
                                hmr: process.env.NODE_ENV === 'development',
                            },
                        },
                        'css-loader', 'sass-loader'
                    ]
                },
                {
                    test: /\.scss$/i,
                    exclude: [
                        path.resolve(__dirname, "assets/css/style.scss"),
                    ],
                    loader: ['style-loader', 'css-loader', 'sass-loader']
                },
                {
                    test: /\.woff(\?v=\d+\.\d+\.\d+)?$/,
                    loader: "url-loader?limit=10000&mimetype=application/font-woff&name=../css/fonts/[name].[ext]"
                }, {
                    test: /\.woff2(\?v=\d+\.\d+\.\d+)?$/,
                    loader: "url-loader?limit=10000&mimetype=application/font-woff&name=../css/fonts/[name].[ext]"
                }, {
                    test: /\.ttf(\?v=\d+\.\d+\.\d+)?$/,
                    loader: "url-loader?limit=10000&mimetype=application/octet-stream&name=../css/fonts/[name].[ext]"
                }, {
                    test: /\.eot(\?v=\d+\.\d+\.\d+)?$/,
                    loader: "file-loader?name=../css/fonts/[name].[ext]"
                }, {
                    test: /\.svg(\?v=\d+\.\d+\.\d+)?$/,
                    loader: "url-loader?limit=10000&mimetype=image/svg+xml&name=../css/fonts/[name].[ext]"
                },
                {
                    test: /\.(jpe?g|png|gif|svg|cur)$/i,
                    loaders: [
                        'file-loader?hash=sha512&digest=hex&name=../img/[name].[ext]',
                        'image-webpack-loader?bypassOnDebug&optimizationLevel=7&interlaced=false'
                    ]
                },
                {test: /\.twig$/, loader: "twig-loader"}
            ]
        },
        resolve: {
            extensions: ['.ts', '.tsx', '.js', '.jsx'],
            alias: {
                'jquery-ui': path.resolve(__dirname, 'node_modules/jquery-ui/ui'),
            }
        }
    };
};

3 个答案:

答案 0 :(得分:0)

几天前,我遇到了同样的问题。您不应将commonjs用作tsconfig的editorOptions.module。尝试将es2015esnext用于moduleResolution节点。

答案 1 :(得分:0)

我从codeandbox react-ts Minimum project中使用rxjs确认了这一点

使用此代码后,我的rxjs捆绑包大小为9.7kb enter image description here

import {  map } from "rxjs/operators";
import { fromEvent } from "rxjs";
...

 const source = fromEvent(document, 'click');
    //map to string with given event timestamp
    const example = source.pipe(map(event => `Event time: ${event.timeStamp}`));
    //output (example): 'Event time: 7276.390000000001'
    const subscribe = example.subscribe(val => console.log(val));

我的tsconfig.json编译器选项是

compilerOptions": {
    "target": "es5",
    "lib": [
      "dom",
      "dom.iterable",
      "esnext"
    ],
    "noImplicitAny": false,
    "allowJs": true,
    "skipLibCheck": true,
    "strictNullChecks": false,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "noEmit": true,
    "jsx": "preserve"
  }

您可以下载相同的代码。构建并分析它。我使用的是source-map-explorer而不是webpack-bundle-analyzer,它需要完整的webpack设置来检查分发包的大小。

注意-在我现有的完整项目中,我尝试进行

"module": "esnext","module": "commonjs",

"moduleResolution": "classic"。但是他们给了我相同的结果。

答案 2 :(得分:0)

我在tsconfig编译器选项中需要的设置是:

"module": "es6",
"moduleResolution": "node",