简体   繁体   中英

How to lazy load components in preact?

My goal is to get two bundles when I build, one for the index.tsx file and another for the lazy.tsx file. I am pretty sure that I am simply missing one or two options somewhere.

GitHub MCVE - example project link

File src/index.tsx

import { render, h } from 'preact';

let a: any = null;
let b = 0;

const App = () => (
  <div>
    <button
      onClick={() => {
        import('./lazy').then(M => {
          console.log('LOADED COMPONENT');
          a = <M.default />;
          b++;
          render(<App></App>, document.body);
        });
      }}
    >
      test
    </button>
    {a} {b}
  </div>
);

render(<App></App>, document.body);

src/lazy.tsx

import { h, FunctionComponent } from 'preact';

console.log('LAZY');

interface LazyProps {}

const Lazy: FunctionComponent<LazyProps> = props => {
  const {} = props;

  return <div>LAZY LOADED COMPONENT</div>;
};

export default Lazy;

Webpack config

{
  entry: {
    index: `${__dirname}/src/index.tsx`
  },
  output: {
    path: resolve(__dirname, 'dist'),
    chunkFilename: '[name].[id].js',
    filename: '[name].bundle.js'
  },

  plugins: [new HtmlWebpackPlugin()],

  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: [/node_modules/]
      }
    ]
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js']
  },
  optimization: {
    minimize: false
  }
}

The above code is working fine without any error but it is not generating multiple bundles as expected with Webpack code splitting.

Edit: here is a link to the working example project

There are two problems with your configuration.

First with your TypeScript configuration:

{
  "compilerOptions": {
    "target": "ES5",
    "module": "ESNext",
    "moduleResolution": "node",
    "strict": true,
    "jsx": "react",
    "jsxFactory": "h",
    "esModuleInterop": true,
    "forceConsistentCasingInFileNames": true
  },

  "include": [
    "src/**/*.tsx"
  ]
}

Two important things properties to remember are:

  1. module : 'ESNext'
  2. moduleResolution : 'node'

Once you set module to ESNext , you cannot write your Webpack config in TypeScript as it expects module to be commonjs . So change it to plain JS with CommonJS format:

const Configuration = require('webpack').Configuration;
const Dev = require('webpack-dev-server').Configuration;
const resolve = require('path').resolve;
const HtmlWebpackPlugin = require('html-webpack-plugin');


const config = {
  entry: {
    index: `${__dirname}/src/index.tsx`
  },
  output: {
    path: resolve(__dirname, 'dist'),
    chunkFilename: '[name].[id].js',
    filename: '[name].bundle.js'
  },

  plugins: [new HtmlWebpackPlugin()],

  module: {
    rules: [
      {
        test: /\.tsx?$/,
        use: 'ts-loader',
        exclude: [/node_modules/]
      }
    ]
  },
  resolve: {
    extensions: ['.tsx', '.ts', '.js']
  },
  optimization: {
    minimize: false
  }
};

module.exports = config;

This should solve your problem.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM