Skip to content

v1 JSX file extension

Jonathan Sharpe edited this page Aug 24, 2024 · 1 revision

The Webpack configuration for the client application uses Babel to transpile the syntax, including JSX, in any .js file. You may prefer to explicitly use the .jsx extension for files containing JSX syntax, but if you do so (for example changing the extension of client/src/pages/About.js to .jsx), without updating the configuration, you will see errors when you try to run or build the client:

  • The module cannot be found:

    ERROR in ./client/src/App.js 2:0-34
    Module not found: Error: Can't resolve './pages/About' in 'path/to/starter-kit/client/src'
    resolve './pages/About' in 'path/to/starter-kit/client/src'
    
  • (If you then change the import to import About from "./pages/About.jsx"; so the module can be found) the module cannot be parsed:

    ERROR in ./client/src/pages/About.jsx 2:1
    Module parse failed: Unexpected token (2:1)
    You may need an appropriate loader to handle this file type, currently no loaders are configured to process this file. See https://webpack.js.org/concepts#loaders
    | const About = () => (
    >       <main role="main">
    

To get this working, you'll have to:

  1. Tell Webpack to resolve modules with the .jsx file extension when importing (so you don't need to explicitly import About from "./pages/About.jsx";);
  2. Tell Webpack to load those modules using Babel (so the JSX can be parsed); and
  3. Update the entry point to not look for index.js specifically (as you'll now presumably be calling it index.jsx).

That looks like:

diff --git a/client/webpack/common.config.js b/client/webpack/common.config.js
index f6757dd..3ae54bc 100644
--- a/client/webpack/common.config.js
+++ b/client/webpack/common.config.js
@@ -1,11 +1,11 @@
 const HtmlWebpackPlugin = require("html-webpack-plugin");
 
 module.exports = {
-	entry: "./client/src/index.js",
+	entry: "./client/src",
 	module: {
 		rules: [
 			{
-				test: /\.js$/,
+				test: /\.jsx?$/,
 				exclude: /node_modules/,
 				use: {
 					loader: "babel-loader",
@@ -33,4 +33,7 @@ module.exports = {
 			template: "./client/src/index.html",
 		}),
 	],
+	resolve: {
+		extensions: [".jsx", "..."],
+	},
 };
Clone this wiki locally