Friday, September 27, 2019

Customize webpack from create-react-app

$ npx create-react-app experiment-react-customized-webpack --scripts-version react-scripts-rewired --use-pnp

Create a directory named shared under src directory

Create randomizer.js under shared directory
export function randomizer() {
    return 4;
}

Create directories components/deeply/nested under src directory

Create SampleComponent.js under src/components/deeply/nested directory
import React from "react";
import { randomizer } from "../../../shared/randomizer";

export function SampleComponent() {
    const a = randomizer();
    return (
        <>
            <strong>I am strong {a}</strong>
        </>
    );
}


Run

It should show on the page:

I am strong 4


Change SampleComponent.js import statement:
import { randomizer } from "../../../shared/randomizer";

to
import { randomizer } from "love/randomizer";

Run

It will fail compiling


Change webpack.config.extend.js code to:

const path = require("path");
/**
 * Project's customized Webpack Configuration Extension
 * ----------------------------------------------------
 *
 * this file is heavily inspired by `react-app-rewired` mechanism.
 *
 * it simply gives you the chance to hook into the default Webpack
 * configuration as it is provided by `create-react-app`, and to
 * change it so to match your project's needs.
 *
 * If you want to check out the default values look into:
 * `./node_modules/marcopeg-react-scripts/config/webpack.config.${env}.js`
 *
 */
module.exports = (webpackConfig, env, { paths }) => {
    // here you can extend your webpackConfig at will
    webpackConfig.resolve.alias = {
        ...webpackConfig.alias,
        love: path.resolve(__dirname, "src", "shared")
    };
    return webpackConfig;
};

Run

It should show on the page:

I am strong 4




No comments:

Post a Comment