美文网首页
本地使用ts配置

本地使用ts配置

作者: storyWrite | 来源:发表于2021-10-30 21:04 被阅读0次

    1.需要安装的依赖

      "dependencies": {
        "html-webpack-plugin": "^5.5.0",
        "ts-loader": "^9.2.6",
        "ts-node": "^10.4.0",
        "tslib": "^2.3.1",
        "typescript": "^4.4.4",
        "webpack": "^5.60.0",
        "webpack-cli": "^4.9.1",
        "webpack-dev-server": "^4.4.0"
      },
      "scripts": {
        "test": "echo \"Error: no test specified\" && exit 1",
        "build": "webpack",
        "serve": "webpack serve"
      },
    

    2. webpack.config.js配置

    const path = require('path').resolve(__dirname, './dist')
    const htmlWebpackPlugin = require('html-webpack-plugin')
    
    module.exports = {
      // 需要添加模式,否则报错
      mode: 'development',
      // 完整相对路径
      entry: './src/main.ts',
      output: {
        path,
        filename: 'bundle.js'
      },
      resolve: {
        // 只匹配ts会导致 无法正常运行js代码
        extensions: ['.ts', '.js', '.cjs', '.json']
      },
      // 使用ts-loader
      module: {
        // 规则是一个数组
        rules: [
          {
            test: /\.ts$/,
            loader: 'ts-loader'
          }
        ]
      },
      plugins: [
        // 插件需要 通过new 进行使用
        new htmlWebpackPlugin({
          template: './index.html'
        })
      ]
    }
    

    3.index.html 模板文件

    <!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>ts Learn</title>
        <script src="./src/main.ts"></script>
      </head>
      <body></body>
    </html>
    

    5. 文件结构

    image.png

    6.遇到问题

    扩展规则少了 js文件的匹配
    Module not found: Error: Can't resolve './log' in '/Users/zdz/Desktop/LearnCode/learn-code/Ts/node_modules/webpack/hot'
    
    htmlWebpackPlugin需要通过new构造使用
    ypeError: Class constructor HtmlWebpackPlugin cannot be invoked without 'new'
        at Object.<anonymous> (/Users/zdz/Desktop/LearnCode/learn-code/Ts/webpack.config.js:28:5)
    

    相关文章

      网友评论

          本文标题:本地使用ts配置

          本文链接:https://www.haomeiwen.com/subject/jzkialtx.html