代码仓库地址
配置JSX
创建pages-Home-index.jsx
import React, { useState, useEffect, useRef } from "react";
const Home = () => {
return <div>我是Home页面</div>;
};
export default Home;
修改src下index.js
import React from "react";
import { render } from "react-dom";
import Home from "./pages/Home/index.jsx";
render(<Home />, document.getElementById("root"));
执行 npm run build
修改webpack.config.js配置
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
entry: "./src/index.js",
output: {
path: path.resolve(__dirname, "dist"),
filename: "index.bundle.js",
},
plugins: [
new HtmlWebpackPlugin({
title: "my-frame",
filename: "./index.html", //filename配置的html文件目录是相对于webpackConfig.output.path路径而言的,不是相对于当前项目目录结构
template: "./src/pages/document.ejs",
templateParameters: {
context: { config: { publicPath: "/public/" } },
},
inject: true, //注入选项 script标签位于html文件的 body 底部
hash: true, //给生成的 js 文件一个独特的 hash 值
}),
],
//定义多个规则来匹配对应的模块,然后给对应的模块应用指定的loader
//重置顺序:一组 Loader 的执行顺序默认是从右到左执行,通过 enforce 选项可以让其中一个 Loader 的执行顺序放到最前或者最后
module: {
rules: [
{
test: /\.(js|jsx)$/, // 注意test的值不是一个字符串,而是一个正则
exclude: /(node_modules|bower_components)/, // 排除这两个文件不需要打包
// 使用babel-loader编译js代码
use: [
{
loader: "babel-loader",
options: {
presets: ["@babel/preset-env"],
},
},
],
},
],
},
};
执行npm run build 打包成功。
发现在index.js里面导入Home组件的时候是使用
import Home from "./pages/Home/index.jsx";
我们一般都是使用的是
import Home from "./pages/Home";
那么.jsx能不能像.js文件一样,省略后缀名,也能解析?
能。需要配置 webpack 的resolve:
暂时只需要配置该配置下的两个配置项:
extensions
mainFiles
修改webpack.config.js
const path = require("path");
const HtmlWebpackPlugin = require("html-webpack-plugin");
module.exports = {
entry: "./src/index.js",
output: {
path: path.resolve(__dirname, "dist"),
filename: "index.bundle.js",
},
plugins: [
new HtmlWebpackPlugin({
title: "my-frame",
filename: "./index.html", //filename配置的html文件目录是相对于webpackConfig.output.path路径而言的,不是相对于当前项目目录结构
template: "./src/pages/document.ejs",
templateParameters: {
context: { config: { publicPath: "/public/" } },
},
inject: true, //注入选项 script标签位于html文件的 body 底部
hash: true, //给生成的 js 文件一个独特的 hash 值
}),
],
resolve: {
// 要解析的文件的扩展名
extensions: [".js", ".jsx", ".json"],
// 解析目录时要使用的文件名
mainFiles: ["index"],
},
//定义多个规则来匹配对应的模块,然后给对应的模块应用指定的loader
//重置顺序:一组 Loader 的执行顺序默认是从右到左执行,通过 enforce 选项可以让其中一个 Loader 的执行顺序放到最前或者最后
module: {
rules: [
{
test: /\.(js|jsx)$/, // 注意test的值不是一个字符串,而是一个正则
exclude: /(node_modules|bower_components)/, // 排除这两个文件不需要打包
// 使用babel-loader编译js代码
use: [
{
loader: "babel-loader",
options: {
presets: ["@babel/preset-env"],
},
},
],
},
],
},
};
执行npm run build 打包成功。