Babel.js 语法错误:不能在模块webpack-typescript外部使用import语句

k2fxgqgv  于 2022-12-08  发布在  Babel
关注(0)|答案(2)|浏览(172)

下面是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"
  ]
}
siv3szwd

siv3szwd1#

在我的例子中,我必须在tsconfig.json中更改为"module": "commonjs",。请参阅https://www.typescriptlang.org/tsconfig#module

jckbn6z7

jckbn6z72#

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

相关问题