语法错误:无法在模块外部使用导入语句 webpack-typescript。

6

以下是webpack.config.ts文件:

// const path = require("path");
import path from "path";
import HtmlWebpackPlugin from "html-webpack-plugin";
import CopyWebpackPlugin from "copy-webpack-plugin";
import webpack from "webpack";

import WebpackDevServer from "webpack-dev-server";

declare module "webpack" {
    interface Configuration {
        devServer?: WebpackDevServer.Configuration;
    }
}
const config: webpack.Configuration = {
  mode: "development",
  target: "web",
  entry: ["regenerator-runtime/runtime", "./src/index.tsx"],
  output: {
    filename: "bundle.js",
    path: path.join(__dirname, "build"),
    publicPath: "/",
  },
  resolve: {
    extensions: [".ts", ".tsx", ".js", ".css"],
    alias: {
      // add as many aliases as you like!
      components: path.resolve(__dirname, "src/components"),
    },
    fallback: {
      // path: require.resolve("path-browserify"),
      fs: false,
      assert: require.resolve("assert/"),
      os: require.resolve("os-browserify/browser"),
      constants: require.resolve("constants-browserify"),
    },
  },
  devtool: "eval-cheap-source-map",
  module: {
    rules: [
      { test: /\.(ts|tsx)/, loader: "babel-loader", exclude: /node_modules/ },
      { test: /\.css$/, use: ["style-loader", "css-loader"] },
      {
        test: /\.(woff(2)?|ttf|eot)(\?v=\d+\.\d+\.\d+)?$/,
        use: [
          {
            loader: "file-loader",
            options: {
              name: "[name].[contenthash].[ext]",
              outputPath: "fonts/",
            },
          },
        ],
      },
      {
        test: /\.svg$/,
        use: [
          {
            loader: "svg-url-loader",
            options: {
              limit: 10000,
            },
          },
        ],
      },
    ],
  },
  devServer: {
    contentBase: path.join(__dirname, "build"),
    historyApiFallback: true,
    overlay: true,
  },

  plugins: [
    new HtmlWebpackPlugin({
      title: "esBUild",
      template: "src/index.html",
    }),
    new CopyWebpackPlugin({
      patterns: [{ from: "assets", to: "assets" }],
    }),
    new webpack.ProvidePlugin({
      process: "process/browser",
      Buffer: ["buffer", "Buffer"],
      React: "react",
    }),
  ],
};

export default config;

以下是 tsconfig.json:

{
  "compilerOptions": {
    // The standard typing to be included in the type checking process.
    "lib": ["dom", "dom.iterable", "esnext"],
    // Whether to allow JavaScript files to be compiled.
    "allowJs": true,
    //This allows default imports from modules with no default export in the type checking process.
    "allowSyntheticDefaultImports": true,
    // Whether to skip type checking of all the type declaration files (*.d.ts).
    "skipLibCheck": true,
    // This enables compatibility with Babel.
    "esModuleInterop": true,
    "strict": true,
    // Ensures that the casing of referenced file names is consistent during the type checking process.
    "forceConsistentCasingInFileNames": true,
    //  This allows modules to be in .json files which are useful for configuration files.
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "isolatedModules": true,
    "module": "es6",
    "target": "es5",
    "sourceMap": true,
    "noEmit": true,
    "jsx": "react",
    "baseUrl": "src",
    "paths": {
      "components": ["components/*"]
    }
  },
  "include": ["src"]
}

我遇到的错误信息如下:

import path from "path";
^^^^^^

SyntaxError: Cannot use import statement outside a module

我谷歌了一下,看到有些人建议添加"type":"module",但是没有起作用。

在tsconfig.json中

 "module": "es6" /* Specify module code generation: 'none', 'commonjs', 'amd', 'system', 'umd', 'es2015', 'es2020', or 'ESNext'. */,

我尝试了每个选项,但仍然不起作用。

如果我放弃typescript配置,改用common.js设置webpack,它就能正常工作。

还有babelrc文件。

{
  "presets": [
    "@babel/preset-react",
    "@babel/preset-env",
    "@babel/preset-typescript"
  ],
  "plugins": [
    "@babel/plugin-proposal-class-properties",
    "@babel/plugin-proposal-object-rest-spread"
  ]
}


你在什么时候/地点遇到了这个错误?是在构建过程中吗? - Felix Kling
@FelixKling 是的,当 Webpack 编译时。 - Yilmaz
有可能webpack不会将配置作为模块加载,而是以其他方式加载。但这只是我的猜测,我没有更多的见解。 - Felix Kling
3个回答

0
在我的情况下,我必须安装插件的 TypeScript 类型(vscode 在重新启动 IDE 后建议这样做)。
例如:
对于 dotenv-webpack 包,我安装了 @types/dotenv-webpack。

0

0
请参考Webpack配置文档的this部分:

以上示例假定您在tsconfig.json文件中使用新的esModuleInterop和allowSyntheticDefaultImports编译器选项,且TypeScript版本大于等于2.7。
请注意,您还需要检查tsconfig.json文件。如果tsconfig.json中compilerOptions中的模块是commonjs,则设置完成,否则webpack将会出现错误。这是因为ts-node不支持除commonjs之外的任何模块语法。
有三种解决此问题的方法:

  • 修改tsconfig.json。
  • 修改tsconfig.json并添加ts-node的设置。
  • 安装tsconfig-paths。
由于您已经在tsconfig.json中正确设置了"esModuleInterop"和"allowSyntheticDefaultImports"的值,所以要消除错误,您应该执行上述三个选项之一。
第一个建议您将“模块”编译器选项的值更改为“commonjs”。 第二个选项允许您保持“模块”选项的值不变,但应在tsconfig.json中添加ts-node的设置。 第三个选项需要安装额外的软件包和单独的TS配置文件。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接