Moving React classes into separate files

后端 未结 3 1939
庸人自扰
庸人自扰 2021-01-31 03:48

After doing the React tutorial this is my index.html file:




  
    

        
3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-31 04:24

    If you want to create a file for each React class, I would recommend to take a look at webpack. You can develop your React classes as CommonJs modules and it will take care of bundling them together.

    Also, I think it is a good option because you want to use babel to transform your jsx files. This is solved with webpack loaders.

    The basic webpack configuration file would contain something like this:

    webpack.config.js

    var webpack = require('webpack');
    
    module.exports = {
      entry: './src/main.jsx',
      output: {
        // Output the bundled file.
        path: './lib',
        // Use the name specified in the entry key as name for the bundle file.
        filename: 'main.js'
      },
      module: {
        loaders: [
          {
            // Test for js or jsx files.
            test: /\.jsx?$/,
            exclude: /node_modules/,
            loader: 'babel'
          }
        ]
      },
      externals: {
        // Don't bundle the 'react' npm package with the component.
        'react': 'React' 
      },
      resolve: {
        // Include empty string '' to resolve files by their explicit extension
        // (e.g. require('./somefile.ext')).
        // Include '.js', '.jsx' to resolve files by these implicit extensions
        // (e.g. require('underscore')).
        extensions: ['', '.js', '.jsx']
      }
    };
    

    I created a GitHub react-tutorial-webpack repository if you want to have actual code.

提交回复
热议问题