Webpack4+React+Typescript搭建开发环境

发布时间:2019-08-20 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了Webpack4+React+Typescript搭建开发环境脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

2018.10.27补充
1.新增url-loader,解决引用背景图片时产生的bug,

  1. img片404解决:如<img src={require('../../images/avaters/avatar.jpg')} />

············································································
1.先看下目录结构

clipboard.png

2.首先,初始化package.json,运行npm inIT,这个不用多说

3.在根目录新建webpack.config.js文件
//创建基本的出入口

modules.exports = {
    //模式:开发模式
    mode:"development"
    entry: path.join(__dirname, './src/index'), //入口
    output: { //出口
        filename: '[hash].bundle.js',
        path: path.resolve(__dirname, './dist')
    },
    module:{
    
    }
}

接下来配置webpack的模块module,这些选项决定了如何处理项目中的不同类型的模块。
重点配置一下module.rules选项,这个能够对模块(module)应用 loader,或者修改解析器(parser)。
module.rules是个数组

modules.exports = {
    module:{
        rules:[
        //ts-loader 用来解析ts文件
        //需要安装以下依赖
        //npm install ts-loader --save-dev
        //npm install tyPEscript --save-dev
        //安装react相关依赖
        //npm install --save-dev react react-dom @types/react @types/react-dom
            {
                test: /.tsx?$/,
                exclude: /node_modules/,//不解析node_modules
                loader: 'ts-loader'
            },
            //加载json,png等文件
            //安装npm install --save-dev file-loader
            {
               test: /.[(png)|(obj)|(json)]$/,
               loader: "file-loader" 
            },
            //加载css
            //安装npm install --save-dev css-loader
            //npm install style-loader --save-dev
            {
               test: /.css$/,
               use: ['style-loader', 'css-loader']
            },
        ]
    }
}
如果需要使用.less,或者在家字体文件,配置相关的loader,每个loader都有丰富的配置选项,可以研究一下按需配置

接着是resolve选项,这些选项能设置模块如何被解析。
方便的比如alias选项,它可以该importrequire设置别名,应用官网例子如下
module.exports = {
  //...
  resolve: {
    alias: {
      Utilities: path.resolve(__dirname, 'src/utilities/'),
      Templates: path.resolve(__dirname, 'src/templates/')
    }
  }
};

现在,替换「在导入时使用相对路径」这种方式,就像这样:

import Utility From '../../utilities/utility';
修改为别名
import Utility from 'Utilities/utility';

最关键的我觉得还是extensions 选项,自动解析确定的扩展

modules.exports={
    resolve: {
        //下面后缀的文件导入时可以省略文件名,js必须要有,否则会react.js文件会无法被解析
        extensions: [".ts", ".tsx", ".js"]
     },
     devtool: 'source-map', //调试工具,不同模式构建速度不同,source-map适合生存环境,开发环境用eval-source-map
     //安装依赖
     //npm install --save-dev webpack-dev-server
      devServer: {
          //告诉服务器从哪个目录中提供内容。只有在你想要提供静态文件时才需要
        contentBase: path.resolve(__dirname, "dist"),
        comPress:true, //是否压缩
        port:8080, //端口号
        host:'0.0.0.0', //外部服务器可以访问
        open:true //是否运行时打开浏览器
      },
      plugins: [
       //该插件将为你生成一个HTML5文件,其中包括使用script标签的body中的所有webpack包
       //安装npm install --save-dev html-webpack-plugin
        new HtmlWebpackPlugin({
          title: '标题',//用于生成的HTML文档的标题
          template: './index.html', //默认index.html位置
        })
  ]
}
package.json相关配置
"scripts": {
    "dev": "webpack-dev-server",
    "build": "webpack"
  },

tsconfig.json配置

{
  "compilerOptions": {
    "jsx": "react",
    "lib": ["es6", "dom"],
    "rootDir": "src",
    "module": "commonjs",
    "target": "ES5",
    "sourceMap": true,
    "moduleResolution": "node",
    "noImplicitReturns": true,
    "noImplicitThis": true,
    "noImplicitAny": true,
    "strictNullChecks": true
  },
  "include": [
    "./src"
  ],
  "exclude": [
    "node_modules",
    "build"
  ]
}

index.html

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=Edge">
  <title>哈哈</title>
</head>
<body>
  <div id="app"></div>
</body>
</html>

index.tsx

import * as React from "react"
import * as ReactDOM from "react-dom"


ReactDOM.render(
  <div>Hello World</div>,
  document.getElementById("app")
)

运行npm run dev即可运行,默认打开localhost:8080;

以上是开发环境教程,其中还有更加丰富的功能插件和配置需要按需添加配置
网站的webapack代码如下

const path = require('path');
const CleanWebpackPlugin = require('clean-webpack-plugin');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  mode: 'development',
  entry: path.join(__dirname, './src/index'),
  output: {
    filename: '[hash].bundle.js',
    path: path.resolve(__dirname, './dist')
  },
  module: {
    rules: [
      {
        test: /.tsx?$/,
        exclude: /node_modules/,
        loader: 'ts-loader',
        options: {
          transpileOnly: true,
          experimentalWatchApi: true,
        }
      },
      {
        test: /.[(png)|(obj)|(json)]$/,
        loader: "file-loader"
      },
      //样式加载 css
      {
        test: /.css$/,
        use: ['style-loader', 'css-loader']
      },
      //解析URL
       {
        test: /.(woff|woff2|jpg|png)$/,
        use: {
            loader: 'url-loader',
            options: {
                name: 'imanges/[hash].[ext]',
                limit: 5000,
                mimetype: 'application/font-woff'
            }
        },
      //样式加载 less
      {
        test: /.less$/,
        use: [{
          loader: "style-loader"
        },
        { loader: 'css-loader', options: { sourceMap: false } },
        {
          loader: "less-loader",
          options: {
            strictMath: true,
            noIeCompat: true
          }
        }
        ]
      },
    ]
  },
  resolve: {
    extensions: [".ts", ".tsx", ".js"]
  },
  devtool: 'source-map',
  devServer: {
    contentBase: path.resolve(__dirname, "dist"),
    comPRess:true,
    port:8080,
    host:'0.0.0.0'
  },
  plugins: [
    // new CleanWebpackPlugin(['dist']),
    new HtmlWebpackPlugin({
      title: 'Zoe',
      template: './index.html',
    })
  ]
};

附:接下来将发布怎么搭建个人网站。。。。

脚本宝典总结

以上是脚本宝典为你收集整理的Webpack4+React+Typescript搭建开发环境全部内容,希望文章能够帮你解决Webpack4+React+Typescript搭建开发环境所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。