簡體   English   中英

使用webpack從主捆綁包中排除JSON文件以進行react-lottie

[英]Exclude JSON files from the main bundle with webpack for react-lottie

在我們的網絡應用中,我們有一些JSON文件,每個文件的行數約為10-80k。 這些已包含在我們的主要捆綁包中。 這些由名為react-lottie的動畫插件使用。

我們的webpack.config.js的示例

module.exports = {
  entry: ["./src/index.js"],
  module: {
    rules: [
      { test: /\.(js|jsx)$/, exclude: /node_modules/, use: ["babel-loader"] },
      {
        test: /\.(jpg|png|gif|ico)$/,
        use: {
          loader: "file-loader",
          options: { name: "[path][name].[hash].[ext]" }
        }
      }
    ]
  },
  resolve: { extensions: ["*", ".js", ".jsx"] },
  output: {
    path: __dirname + "/dist",
    publicPath: "/",
    filename: "[name].[hash].js"
  },
  plugins: [
    new webpack.HotModuleReplacementPlugin(),
    new HtmlWebpackPlugin({ hash: false, template: "src/index.html" }),
    new DashboardPlugin(),
    new CopyWebpackPlugin([
      {
        from: "src/components/Assets/BookingBar.js",
        to: "assets/BookingBar.js"
      }
    ]),
    new BundleAnalyzerPlugin()
  ],
  devServer: {
    contentBase: "./dist",
    hot: true,
    historyApiFallback: true,
    port: 4000
  }
};

預期的行為是什么?

應該有一種從主捆綁包中排除.json文件的方法。 我已經嘗試了File-Loader,json-loader和const someJson = require(./ someJson)

其他相關信息:Webpack版本:4.16.1 Node.js版本:10.12.0

操作系統:Mac OS 10.14 Mojave

下面的答案(我如何解決)。 沒有任何數據,我無法初始化抽獎活動。

預期的行為是JSON將被捆綁,因為大概在運行時需要同步。 JSON數據不同於圖像文件之類的東西,它們是由瀏覽器異步加載的,因為它們是通過src屬性等呈現在頁面上的。

如前所述,您應該使用代碼拆分。 如果您安裝並使用@babel/plugin-syntax-dynamic-import插件,則最新版本的Webpack支持動態 @babel/plugin-syntax-dynamic-import

npm install --save-dev @babel/plugin-syntax-dynamic-import

然后在babel.config.js

module.exports = {
  ...
  plugins: [
    "@babel/plugin-syntax-dynamic-import"
  ]
  ...
};

假設您有一個React組件,它可能需要一些JSON數據,但不需要作為捆綁包的一部分同步加載。 您的代碼拆分版本可能如下所示:

import React from 'react';
import myJSON from './myJSON.json';

export default class MyComponent extends React.Component {
  render() {
    return <div>{JSON.stringify(myJSON, null, 2)}</div>
  }
}

相反,您可以使用動態導入-基本上是運行時導入,它返回一個Promise,您可以使用該異步加載與包分開的分塊數據:

import React from 'react';
import myJSON from './myJSON.json';

export default class MyComponent extends React.Component {
  state = {data: {}};
  componentDidMount() {
    import(/* webpackChunkName: 'myJSON' */ './myJSON.json')
      .then((data) => {
        this.setState({data});
      });
  }
  render() {
    return <div>{JSON.stringify(this.state.data, null, 2)}</div>
  }
}

另外,您可以使用React的新的lazySuspense API(v16.6.0及更高版本)來動態導入從捆綁包中分塊出來的React組件 如果您想將組件及其對應的JSON數據分塊在一起,但又與主捆綁包分開,則可能更可取:

// MyComponent.jsx
import React from 'react';
import myJSON from './myJSON.json';

export default class MyComponent extends React.Component {
  render() {
    return <div>{JSON.stringify(myJSON, null, 2)}</div>
  }
}

// SomeParent.jsx
import React, {lazy, Suspense} from 'react';
const MyComponent = lazy(() => import(/* webpackChunkName: 'MyComponent' */ './MyComponent'));

export default class SomeParent extends React.Component {
  render() {
    return <div>
      <Suspense fallback={<div>Loading...<div>} >
        <MyComponent />
      </Suspense>
    </div>;
  }
}

在上面的示例中, <MyComponent />及其相應的代碼(包括JSON數據)僅在組件在運行時實際呈現時才加載。

最終,我接受了上面的答案,但是沒有任何JSON數據就無法初始化彩票。 我最終這樣做:

import React, { PureComponent } from "react"
import Lottie from 'react-lottie'

export default class AnimationAutomatedCommunication extends PureComponent {

  constructor(props) {
    super(props)
    this.state = {
      animation: <div />
    }
  }

  async componentDidMount() {
    const animation = await import(/* webpackChunkName: "AnimationAutomatedCommunication" */ './JsonData/AnimationAutomatedCommunication.json')
     const defaultOptions = {
       loop: true,
       autoplay: true,
       animationData: animation.default
     }
    this.setState({
      animation: <div className={this.props.className}>
        <Lottie key="lottie-win-jobs" options={defaultOptions}
                isStopped={this.props.isStopped} />
      </div>
    })
  }

  render() {
    return (
      <React.Fragment>
        {this.state.animation}
      </React.Fragment>
    )
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM