Finally I got it!
By default npx create-react-app
create a structure with a lot of configurations, folders and files to make easy start to coding an app with React, one of this configs is setting up webpack to create a "build" directory when we type "npm build" with all the components of our app and allow us to deploy it everywhere, but in my case, I just needed to distribute a .js file with the widget that I am creating, this .js file could be placed inside of a in any HTML page and the widget will work apart, independent of the page, to make this I followed these steps:
- First, I need to change in the "package.json" file the "scripts" section, to indicate to webpack will make not only the "build" directory, also a bundle.js with all the CSS, images, components.
"scripts": {
"start": "react-scripts start",
"build": "npm run build:react && npm run build:bundle",
"build:react": "react-scripts build",
"build:bundle": "webpack --config webpack.config.js",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
Notice that I have replaced the "bundle" script, indicating that will execute "build:react" and "build:bundle"
- As we see, "build:bundle" will take the configuration of "webpack.config.js", in our initial confuguration we dont have this file, because webpack is automatically configured by "npx create-react-app", so, we need to create this file in the root path of our app and create a configuration to tell webpack that needs to bundle everything, my configuration is this:
const UglifyJsPlugin = require("uglifyjs-webpack-plugin");
module.exports = {
entry: {
entry: './src/index.js',
},
output: {
filename: "build/static/js/WidgetCL.js",
},
module: {
rules: [
{
test: /\.css$/,
use: ["style-loader", "css-loader"],
},
{
test: /\.m?js$/,
exclude: /(node_modules)/,
use: {
loader: 'babel-loader',
options: {
presets: ['@babel/preset-env'],
plugins: ['@babel/plugin-transform-runtime']
}
}
}
],
},
plugins: [new UglifyJsPlugin()],
}
I am telling webpack that it needs to take the "index.js" file created automatically by npx as entry point, also webpack will create a WidgetCL.js as output, the interesting part is in the "module" section, after a few hours or issues, I could configure two "Loaders", one for the .css files and the other one for all the .js components in my widget, using Babel as Loader.
- To use Babel I needed to create a file named .babelrc in the root path of my project and configure it in this way:
{
"presets": [
"@babel/react" ,
"@babel/env"
],
"plugins": [
"@babel/plugin-proposal-class-properties"
]
}
After this, I just open a terminal and type "npm run build", then webpack creates the "build" folder and also a "dist" folder with my .js file inside.