webpack构建多页面react项目(webpack+typescript+react)

 目录介绍

  src:里面的每个文件夹就是一个页面,页面开发相关的组件、图片和样式文件就存放在对应的文件夹下。

  tpl:里面放置模板文件,当webpack打包时为html-webpack-plugin插件提供模板。

  tsconfig.json:typescript的配置文件,需要自己新建并编写。

  webpack.config.js:webpack的配置文件,需要自己新建并编写。

  config:文件夹下的index.dev.js用来配置开发模块,index.js配置发布模块。将会在webpack.config.js中引用。index.dev.js是index.js的子集,index.js包含了所有的页面。

 index.dev.js

module.exports = {
    page2: {
        title: "hello world!",
        tpl: "index"
      }
};

index.js

module.exports = {
    page1: {
      title: "hello world!",
      tpl: "index"
    },
    page2: {
      title: "hello world!",
      tpl: "index"
    }
  };
  

npm初始化项目

  执行npm init命令,填写完基本信息后会生成一个package.json文件,"dependencies"属性是在安装依赖包附带--save参数时生成的,“devDependencies”属性是在安装开发依赖包附带--save-dev参数时生成的。

npm init

package.json文件

{
  "name": "react-demo",
  "version": "1.0.0",
  "description": "react+typescript+webpack项目",
  "private": true,  //设置为true,那么npm将拒绝发布它,防止私人存储库意外发布
  "scripts": {      // 自定义脚本,通过npm run执行脚本
    "start": "webpack-dev-server --mode development --cfg dev",  //启动web服务器,cfg是自定义参数,赋值为dev。
    "build": "webpack --mode production"
  },
  "keywords": [
    "react",
    "typescript",
    "webpack"
  ],
  "author": "chencong",
  "license": "ISC",
  "devDependencies": {
    "clean-webpack-plugin": "^1.0.1",
    "html-webpack-plugin": "^3.2.0",
    "ts-loader": "^5.3.3",
    "typescript": "^3.3.3",
    "webpack": "^4.29.3",
    "webpack-cli": "^3.2.3",
    "webpack-dev-server": "^3.1.14",
    "yargs": "^13.1.0"
  },
  "dependencies": {
    "react": "^16.8.2",
    "react-dom": "^16.8.2"
  }
}

添加react

npm install --save react react-dom

添加typescript

安装typescript编译器和loader

npm install --save-dev typescript ts-loader

   安装完成后需要编写配置文件,在项目中新建tsconfig.json文件。配置完后就该ts-loader登场了,在webpack.config.js中配置loader,将项目中所有的用typescript语法编写的文件都用ts-loader处理,处理的依据就是tsconfig.json文件。还有一点需要提一下,项目可以不用babel进行转码了,因为ts-loader已经帮我们处理了,tsconfig.json中“target”: “es5”就是转码成es5的配置,"jsx": "react"就是对jsx的支持,不需要用babel-preset-react进行转码。(typescript配置文档)

{
  "version": "1.0.0",
  "compilerOptions": {
    "baseUrl": "./",  //解析非相对模块的基准目录
    "paths": {  //路径映射,如在文件中使用‘~/’相当于‘src/’
      "~/*": ["src/*"]
    },
    "module": "esnext",  //指定生成哪个模块系统的代码
    "target": "es5", //生成es5的js文件
    "jsx": "react",  //在tsx文件里支持jsx
    "sourceMap": true,
    "moduleResolution": "node", //决定如何处理模块
    "allowJs": true,  //允许编译js文件
    "strictNullChecks": false,  //在严格的 null检查模式下, null和 undefined值不包含在任何类型里,只允许用它们自己和 any来赋值(有个例外, undefined可以赋值到 void)
    "lib": ["es2015", "dom", "es2015.promise"]  //编译过程中需要引入的库文件的列表
  },
  "include": ["src/**/*"], //编译包含在  src及其子目录下的所有匹配的文件
  "exclude": ["dist", "node_modules"]  //编译时排除 dist、node_modules文件夹
}

添加webpack

  执行以下命令添加webpack,使用webpack 4.X的命令行需要单独安装命令行工具,所以也要安装webpack-cli。html-webpack-plugin插件帮助我们在打包时根据模板生成html文件,还需注意模板中title标签的写法,应为<title><%= htmlWebpackPlugin.options.title%></title>。clean-webpack-plugin插件会在项目打包前删除指定的文件,通常用来删除旧的打包文件。yargs包提供了获取命令行中参数的对象。

npm install --save-dev webpack webpack-cli html-webpack-plugin clean-webpack-plugin yargs

接下来编写webpack的配置文件,在项目中新建配置文件webpack.config.js。(webpack文档)

const path = require("path");
const argv = require("yargs").argv;  //获取命令行中参数的对象
const HtmlWebpackPlugin = require("html-webpack-plugin");
const CleanPlugin = require("clean-webpack-plugin");
const webpack = require("webpack");

const isDev = argv.cfg && argv.cfg === "dev";  //是否为开发模式,如果输入yarn start执行"webpack-dev-server --mode development --cfg dev",argv.cfg获取参数的值为dev。
let compileConfig = "index";
if (isDev) {
  compileConfig = "index." + argv.cfg;
}

const buildConfig = require(`./config/${compileConfig}`); // 开发模式下,引入index.dev.js中的配置信息。生产模式下,引入index.js中的配置信息
const modules = Object.keys(buildConfig);
const entry = Object.create(null);
const htmlPlugins = [];
if (modules.length > 0) {
  for (let srcModule of modules) {
    entry[srcModule] = path.resolve(__dirname, `./src/${srcModule}`);  // 多页面应用webpack配置文件entry属性的值
    htmlPlugins.push(  // html-webpack-plugin插件生成html的配置
      new HtmlWebpackPlugin({
        title: buildConfig[srcModule]["title"],
        filename: `${srcModule}/index.html`,
        template: path.resolve(__dirname, "./tpl/index.html"),
        chunks: [srcModule]
      })
    );
  }
}

const config = {
  entry,
  output: {
    publicPath: "/dist/",
    filename: "[name].[hash].js",
    path: path.resolve(__dirname, "dist")
  },
  module: {
   rules: [
    { // 除了node_modules文件夹中的文件,所有的tsx文件都用ts-loader处理
     test: /.tsx?$/,
     use: "ts-loader",
     exclude: /node_modules/
    }
   ] 
} plugins: [
new CleanPlugin(['dist']), ...htmlPlugins], resolve: { extensions: [".tsx", ".ts", ".js"] }, devtool: isDev ? "source-map" : false // 值为source-map时,方便在浏览器中使用react开发工具调试 }; if (isDev) { // 开发模式时,启动web服务 config.devServer = {
  contentBase: './dist', // 告诉服务器那个文件夹提供静态资源 port:
9000, open: true, hot: false, // 启用webpack中的热替换特性,这里我们不用热替换(不刷新整个页面的情况下更新部分更改)而用热更新(整个页面自动刷新) openPage: `dist/${modules[0]}` // 打开index.dev.js配置中的第一个页面 }; // config.plugins.push(new webpack.HotModuleReplacementPlugin()); // 热替换需要的插件 } module.exports = config;

关于样式

  webpack在打包除javascript以外的静态资源时,需要用loader预处理。在实际开发中我通常用less来写样式,所以先要用less将less文件编译成css ,然后用css-loader预处理css文件。最后还需要用mini-css-extract-plugin插件将css从webpack打包后的文件中抽离出来按需加载,或者用style-loader将css以内联的方式加载,mini-css-extract-plugin插件和style-loader不能同时使用,推荐使用前者将样式抽离出来按需加载。

安装

npm install --save-dev css-loader less-loader less mini-css-extract-plugin

webpack.config.js中配置

  module: {
    rules: [
       ...
      {
        test: /.less$/,
        use: [  // webpack会从右往左加载loader,所有书写loader时有顺序要求
       // {
    //  loader: 'style-loader' //style-loader不能和mini-css-extract-plugin同时使用
    // }
MiniCssExtractPlugin.loader, {
        loader: 'css-loader'
      },
{
        loader: 'less-loader'
      }
] } ... ] }, plugins: [ ... new MiniCssExtractPlugin({ filename: "[name].[hash].css", chunkFilename: "[name].[hash].css" }), ... ],

autoprefixer

  写样式时为了兼容不同的浏览器,css3的特性需要加前缀,例如:

-moz-  对应  Firefox, 
-webkit-  对应  Safari and Chrome
-o-  对应  Opera
-ms-  对应  Internet Explorer

如果自己手动地写就会很麻烦,于是就有了autoprofixer帮我们自动添加这些前缀。postcss-flexbugs-fixe是用来修复一些flexbox的bug。

安装

cnpm install --save-dev postcss-loader autoprefixer postcss-flexbugs-fixes

webpack.config.js中配置

  module: {
    rules: [
       ...
      {
        test: /.less$/,
        use: [
          // {
          //   loader: "style-loader" 
          // },
          MiniCssExtractPlugin.loader,
          {
            loader: "css-loader"
          },
          {
            loader: "less-loader"
          },
          {
            loader: "postcss-loader",
            options: {
              ident: "postcss",  // postcss-loader中options里使用了function、require时需要ident属性,可以是任意值
              plugins: () => [
                require("postcss-flexbugs-fixes"),
                autoprefixer({
                  browsers: [
                    ">1%",
                    "last 4 versions",
                    "Firefox ESR",
                    "not ie < 9"
                  ],
                  flexbox: "no-2009"  // false将禁用flexbox属性前缀。或flexbox:“no-2009”将仅为最终版本和IE版本的规范添加前缀。
                })
              ]
            }
          },
        ]
      }
    ]
  },    

图片处理 

  页面引入图片如:background: url(,/images/logo.png)  ,webpack打包时无法解析图片报错,这时就需要loader来处理图片。

ur-loader可以将图片转化成base64的格式,以减少请求次数。。

安装

npm i -D url-loader

webpack.config.js配置

module: {
  rules: [
    ...
    {
        test: /.png|jpg|gif|jpeg|svg/,
        use: [
            {
                loader: 'url-loader',
                options: {
                    limit: 10000,   // 当图片小于limit(单位:byte)时图片转换成base64,大于limit时其表现行为等于file-loader
                  name: './images/[name].[hash:8].[ext]'   // 当图片大于limit时起作用 ,'./images'表示图片打包的路径相对于output.path,[name]表示图片的名称,[hash:8]表示9位数的hash值,[ext]表示保持原来的后缀名
         } } ] } ] }

  以上就是构建多页面应用的所有配置了,如有疑问或有更好的建议欢迎交流!

                                                                         

                              

原文地址:https://www.cnblogs.com/chen-cong/p/10373486.html