webpack配置打包js,jsx,ESLint插件、TypeScript、TSX

前言

webpack版本:

"webpack": "5.23.0",
"webpack-cli": "4.5.0"

 

webpack输入代码支持IE

因为webapck5已经不兼容IE了,如果我们需要在5中兼容IE则需要另行配置。

在项目中创建.browserslistrc文件:

[production]
> 1%
ie 9

[modern]
last 1 chrome version
last 1 firefox version

[ssr]
node 12

文件内容的意思是,最低需要支持ie9,支持一个最新的chrome版本和一个最新的firefox版本,ssr是在node上使用的配置。webpack在打包的时候会自动读取这个配置文件,并按配置文件操作。

IE并不能完全支持,因为IE上面没有Promise类。

 

用babel-loader打包JS

webpack.config.js

module.exports = {
  mode: 'production',
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: [
              ['@babel/preset-env']
            ]
          }
        }
      }
    ]
  }
}

 

用babel-loader打包JSX

webpack.config.js

options: {
  presets: [
    ['@babel/preset-env'],
    ['@babel/preset-react'] // 通过preset-react 支持jsx
  ]
}

 

webpack配置ESLint插件

在项目中创建.eslintrc.js文件

module.exports = {
  extends: ['react-app'],
  rules: {
    'react/jsx-uses-react': [2], // [0]:忽略,[1]:警告,[2]:报错
    // 提示要在 JSX 文件里手动引入 React
    'react/react-in-jsx-scope': [2]
  }
}

 [0]:忽略,[1]:警告,[2]:报错

webpack.config.js 

const ESLintPlugin = require('eslint-webpack-plugin')

module.exports = {
  mode: 'production',
  plugins: [new ESLintPlugin({
    extensions: ['.js', '.jsx'] // 不加 .jsx 就不会检查 jsx 文件了
  })],
  module: {
    rules: [
      {
        test: /\.jsx?$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: [
              ['@babel/preset-env'],
              ['@babel/preset-react', {runtime: 'classic'}]
            ]
          }
        }
      }
    ]
  }
}

 

用babel-loader打包TS

webpack.config.js 

module: {
  rules: [
    {
      test: /\.[jt]sx?$/,
      exclude: /node_modules/,
      use: {
        loader: 'babel-loader',
        options: {
          presets: [
            ['@babel/preset-env'],
            ['@babel/preset-react', {runtime: 'classic'}],
            ['@babel/preset-typescript'] // 加上这一句
          ]
        }
      }
    }
  ]
}

因为TSLint的作者发表声明,不再维护TSLint,所以我们转用ESLint的babel,preset-typescript。 

 

让ESLint支持TypeScript

.eslintrc.js

module.exports = {
  extends: ['react-app'],
  rules: {
    'react/jsx-uses-react': [2],
    // 提示要在 JSX 文件里手动引入 React
    'react/react-in-jsx-scope': [2]
},
  overrides: [{
    files: ['*.ts', '*.tsx'],
    parserOptions: {
      project: './tsconfig.json',
    },
    extends: ['airbnb-typescript'],
    rules: {
      '@typescript-eslint/object-curly-spacing': [0],
      'import/prefer-default-export': [0],
    }
  }]
}

webpack.config.js

plugins: [new ESLintPlugin({
    extensions: ['.js', '.jsx', '.ts', '.tsx'] // 不加 .jsx 就不会检查 jsx 文件了
  })],

 

用babel-loader打包TSX

通过 tsc --init 初始化 tsconfig.json 文件

然后修改tsconfig.json

{
  "compilerOptions": {
    /* Basic Options */
    "target": "es5", 
    "module": "commonjs", 
    "jsx": "react", 
    /* Strict Type-Checking Options */
    "strict": false,  
    "noImplicitAny": true,
    "esModuleInterop": true, 
    "skipLibCheck": true, 
    "forceConsistentCasingInFileNames": true 
  }
}

 

让JS和TS支持@alias

JS 支持@alias

webpack.config.js

const ESLintPlugin = require('eslint-webpack-plugin')
const path = require('path')

module.exports = {
  mode: 'production',
  plugins: [new ESLintPlugin({
    extensions: ['.js', '.jsx', '.ts', '.tsx'] // 不加 .jsx 就不会检查 jsx 文件了
  })],
  // 加下面这一段配置
  resolve: {
    alias: {
      '@': path.resolve(__dirname, './src/')
    }
  },
  ...
}

添加后,既可以在文件中使用@代替相对路径。

import {xxx} from '@/xxx' // 直接引入

TS 支持@alias

.eslintrc.js

rules: {
    'react/jsx-uses-react': [2],
    // 提示要在 JSX 文件里手动引入 React
    'react/react-in-jsx-scope': [2],
    'no-console': [0]
  },
  overrides: [{
    files: ['*.ts', '*.tsx'],
    parserOptions: {
      project: './tsconfig.json',
    },
    extends: ['airbnb-typescript'],
    rules: {
      '@typescript-eslint/object-curly-spacing': [0],
      'import/prefer-default-export': [0],
      'no-console': [0],
      'import/extensions':[0]
    }
  }]
}

tsconfig.json

{
  "compilerOptions": {
    /* Visit https://aka.ms/tsconfig.json to read more about this file */
    "baseUrl": ".",
    "paths": {
      "@/*": ["src/*"]
    },
    ...
}

 

webpack配置完整代码:https://github.com/A-Tione/webpack-config-1

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,首先你需要安装webpack5、react、typescripteslint以及相关的loader和插件。你可以通过以下命令安装它们: ``` npm install webpack webpack-cli webpack-dev-server react react-dom @types/react @types/react-dom typescript @typescript-eslint/eslint-plugin @typescript-eslint/parser eslint eslint-config-airbnb eslint-config-prettier eslint-plugin-import eslint-plugin-jsx-a11y eslint-plugin-prettier eslint-plugin-react eslint-plugin-react-hooks prettier -D ``` 接下来,你需要创建一个webpack配置文件,可以命名为`webpack.config.js`,在该文件中配置webpack相关内容: ```javascript const path = require('path'); const HtmlWebpackPlugin = require('html-webpack-plugin'); module.exports = { entry: './src/index.tsx', output: { path: path.resolve(__dirname, 'dist'), filename: 'bundle.js', }, resolve: { extensions: ['.tsx', '.ts', '.js'], }, module: { rules: [ { test: /\.(ts|tsx)$/, exclude: /node_modules/, use: [ { loader: 'babel-loader', options: { presets: [ '@babel/preset-env', '@babel/preset-react', '@babel/preset-typescript', ], }, }, { loader: 'ts-loader', }, ], }, { test: /\.(js|jsx)$/, exclude: /node_modules/, use: ['babel-loader'], }, { test: /\.css$/, use: ['style-loader', 'css-loader'], }, ], }, plugins: [ new HtmlWebpackPlugin({ template: './public/index.html', }), ], devtool: 'inline-source-map', devServer: { contentBase: './dist', port: 3000, }, mode: 'development', }; ``` 在上面的配置中,我们指定了入口文件为`src/index.tsx`,打包后的输出文件为`dist/bundle.js`。我们还通过resolve属性指定了文件的拓展名,这样在引入文件时就不用指定拓展名了。 在module属性中,我们定义了不同类型文件的loader,例如对于`.tsx`和`.ts`文件,我们使用了`babel-loader`和`ts-loader`,对于`.js`和`.jsx`文件,我们只使用了`babel-loader`。此外,我们还使用了`style-loader`和`css-loader`处理`.css`文件。 在plugins属性中,我们使用了`HtmlWebpackPlugin`插件,用于生成HTML文件。在devServer属性中,我们指定了开发服务器的端口和从哪个文件夹提供内容。 最后,我们使用了`inline-source-map`作为开发模式下的source-map,将模式设置为`development`。 接下来,你需要创建一个`.babelrc`文件,用于配置babel: ```json { "presets": ["@babel/preset-env", "@babel/preset-react", "@babel/preset-typescript"] } ``` 然后,你需要创建一个`.eslintrc.json`文件,用于配置eslint: ```json { "parser": "@typescript-eslint/parser", "plugins": ["@typescript-eslint"], "extends": ["airbnb", "plugin:@typescript-eslint/recommended", "prettier"], "rules": { "prettier/prettier": ["error"], "react/jsx-filename-extension": [1, { "extensions": [".tsx"] }], "import/extensions": ["error", "never", { "svg": "always" }] }, "settings": { "import/resolver": { "node": { "extensions": [".js", ".jsx", ".ts", ".tsx"] } } } } ``` 在上面的配置中,我们使用了`@typescript-eslint/parser`解析Typescript代码,并使用了`@typescript-eslint/eslint-plugin`插件提供的规则。我们还继承了`eslint-config-airbnb`和`eslint-config-prettier`,并使用了一些自定义的规则。 最后,你需要在`package.json`中添加一些scripts,用于启动开发服务器和打包代码: ```json { "scripts": { "start": "webpack serve --mode development", "build": "webpack --mode production" } } ``` 现在你就可以使用`npm start`命令启动开发服务器,使用`npm run build`命令打包代码了。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值