使用导入/导出时出现 webpack 错误

时间:2021-05-20 23:18:29

标签: typescript webpack es6-modules

当我尝试从另一个模块导入函数然后运行该函数时出现错误。我一直在简单的 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

1 个答案:

答案 0 :(得分:0)

要使 webpack 能够解析 typescript 文件,您需要将其添加到 webpack 扩展列表中。

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

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

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