【问题标题】:Getting error with webpack when using import/export使用导入/导出时出现 webpack 错误
【发布时间】:2021-08-10 05:19:01
【问题描述】:

当我尝试从另一个模块导入函数然后运行该函数时出现错误。我一直在对简单的 js 文件执行此操作,但是当我在 TS 上尝试此操作时,它给了我一个错误。 TS有不同的方式吗?

index.ts

import 'normalize.css';
import './sass/style.scss';
import * as _ from 'lodash';
import { foo } from './ty';

foo('bad');

ty.ts

const foo = (ok: string): void => {
console.log(ok);
};

export { foo };

webpack.config.js

const path = require('path');

module.exports = {
  entry: './src/index.ts',
  devtool: 'inline-source-map',
  mode: 'development',
  optimization: {
    usedExports: true,
  },
  module: {
    rules: [
      {
        test: /\.ts$/,
        use: 'ts-loader',
        include: [path.resolve(__dirname, 'src')],
      },
      {
        test: /\.css$/i,
        use: ['style-loader', 'css-loader'],
      },
      {
        test: /\.s[ac]ss$/i,
        use: [
          // Creates `style` nodes from JS strings
          'style-loader',
          // Translates CSS into CommonJS
          'css-loader',
          // Compiles Sass to CSS
          'sass-loader',
        ],
      },
      {
        test: /\.(woff|woff2|eot|ttf|otf)$/i,
        type: 'asset/resource',
      },
    ],
  },
  output: {
    filename: 'main.js',
    path: path.resolve(__dirname, 'dist'),
    clean: true,
  },
};

tsconfig.json

  "compilerOptions": {
    "outDir": "./dist/",
    "sourceMap": true,
    "noImplicitAny": true,
    "module": "commonJS",
    "target": "es5",
    "jsx": "react",
    "allowJs": true,
    "moduleResolution": "node"
  }
}

Here is the screenshot my VS code

【问题讨论】:

    标签: typescript webpack es6-modules


    【解决方案1】:

    为了让 webpack 能够解析 typescript 文件,你需要将它添加到 webpack 扩展列表中。

    默认情况下,webpack 在解析模块时不会查找 .ts 或 .tsx 文件。

    将您的 webpack.config.js 更新为:

    module.exports = {
      ...
      resolve: {
        extensions: ['.ts', '.js', '.json'],
      },
      ...
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-30
      • 2020-09-20
      • 2018-12-27
      相关资源
      最近更新 更多