JIYIK CN >

Current Location:Home > Learning > WEB FRONT-END > React >

Webpack packages ES6 and CommonJs mixed React

Author:JIYIK Last Updated:2025/03/02 Views:

When learning React, I have always used Webpack (ebpack) for packaging. At the beginning, I had no problem using the basic configuration for the basic CommonJs ReactES6 syntax. However, when I recently learned about props in React...other, which is a feature of React ES7, the original basic configuration can no longer meet the requirements. The existing configuration must be upgraded.

Next, I will talk about the upgrade process of my React environment.

When we first use CommonJs syntax, we only need to use the most basic configuration:

$ npm install babel-core babel-loader --save-dev

After installing babel-core and babel-loader, let's write the Webpack configuration file. The default file name is webpack.config.js. Of course, you can use other file names (such as wpconfig.js), just add the --config parameter when using the webpack command:

$ webpack --config wpconfig.js

The configuration file content is as follows

module.exports = {
    entry: {
        module: './src',
    } ,
    output:{
        path: './builds',
        filename: 'onmpw.js',
    },
    module:{
        loaders:[
            {
                test: /\.jsx?$/,
                loader: 'babel',
             },
        ],
    }
};

If you want to use jsx in react code, you must install babel-preset-react and then modify the webpack configuration file

$ npm install babel-preset-react --save-dev

The following is part of the configuration file

{
    test: /\.jsx?$/,
    loader: 'babel-loader',
    query:{
        presets:['react']
    }
}

Next, if you want to use ES6 syntax in React, you need to make your environment support ES6 or ES2015

$ npm install babel-preset-es2015 --save-dev

The following is part of the configuration file

{
    test: /\.jsx?$/,
    loader: 'babel-loader',
    query:{
        presets:['react', 'es2015']
    }
}

Finally, if you want to make your environment support some experimental features of ES7, you can continue to upgrade as follows

$# npm install babel-preset-stage-0 --save-dev

The content of the configuration file is as follows:

{
    test: /\.jsx?$/,
    loader: 'babel-loader',
    query:{
        presets:['react', 'es2015', 'stage-0']
    }
}

In response to the above situations, here is a code snippet that covers these situations.

var FancyCheckbox = React.createClass({
    render: function() {
        var { checked, ...other } = this.props;
        var fancyClass = checked ? 'FancyChecked' : 'FancyUnchecked';
        // `other` 包含 { onClick: console.log } 但 checked 属性除外
        return (
            <div {...other} className={fancyClass} />
        );
    }
});
ReactDOM.render(
  <FancyCheckbox checked={true} onClick={console.log.bind(console)}>
    Hello world!
  </FancyCheckbox>,
  document.getElementById('example')
);

Finally, we need to pay attention. Babel cannot support the separate compilation of all ES6 codes. It needs the support of some runtime environment to achieve it. More typically, the new ES6 built-in methods, such as Set, Map and Promise, must be supported by polyfilled. And the implementation of Babel's parser also requires a series of auxiliary runtime environments. The method of installing polyfilled is as follows

$ npm install babel-polyfilled --save

At the same time, Babel compiles these small helper code directly into your code. This is fine for a single small file. But if you bundle this with Webpack, the duplicate code will result in a very large file. In view of this situation, it is more appropriate to use the babel-runtime package with the transform-runtime plugin instead of these helper tools.

$ npm install babel-runtime --save
$ npm install babel-plugin-transform-runtime --save-dev

Of course, after installing these, we also need to upgrade our Webpack configuration file. The code is as follows:

{
    test: /\.jsx?$/,
    loader: 'babel-loader',
    query:{
        plugins: ['transform-runtime'],
        presets: [ 'react', 'es2015', 'stage-0']
    }
}

Well, all of the above is the configuration of the environment required for several situations of packaging React with Webpack. I hope it will be helpful for everyone to learn React in the future.

For reprinting, please send an email to 1244347461@qq.com for approval. After obtaining the author's consent, kindly include the source as a link.

Article URL:

Related Articles

How to avoid cross-origin (CORS) issues in React/Next.js

Publish Date:2025/03/17 Views:170 Category:NETWORK

In this article, we will introduce how to avoid cross-origin (CORS) issues in React/Next.js. Cross-origin resource sharing (CORS) is a protocol that defines how web requests should be handled when crossing different URLs.

React Tutorial - Transferring Props

Publish Date:2025/03/16 Views:188 Category:React

React transfers Props. Props are generated when components are encapsulated. Components expose some properties (Props) to the outside world to complete some functions.

React Tutorial: Props Anti-Pattern

Publish Date:2025/03/16 Views:187 Category:React

React's Props anti-pattern, using Props to generate state in getInitialState is an anti-pattern - Anti-Pattern.

React Tutorial - Props Validation

Publish Date:2025/03/16 Views:102 Category:React

Props validation is a very useful way to use components correctly. It can avoid many bugs and problems as your application becomes more and more complex. In addition, it can make your program more readable.

Why do you need to bind event handlers in React Class Components?

Publish Date:2025/03/16 Views:60 Category:React

When using React, we must have come across control components and event handlers. We need to use `.bind()` in the constructor of the custom component to bind these methods to the component instance. As shown in the following code:

Solution to the error "does not contain a default export" in React

Publish Date:2025/03/16 Views:191 Category:React

When we try to use `default import` to import from a module that does not have a `default export`, we get a "does not contain a default export" error. To fix the error, make sure the module has named exports and wrap the import in curly braces, e.g.

Scan to Read All Tech Tutorials

Social Media
  • https://www.github.com/onmpw
  • qq:1244347461

Recommended

Tags

Scan the Code
Easier Access Tutorial