You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

将TypeScript模块导入JS文件时出现引用错误求助

问题解决方案

一、核心问题根源

你的项目采用CommonJS模块管理,但TypeScript默认编译输出CommonJS格式的模块(module.exports),而JavaScript文件使用了ES模块的import语法,两者模块系统不兼容,导致找不到命名导出Grid。


二、不使用打包工具的解决办法

1. 调整TS编译配置,输出ES模块

修改tsconfig.json,指定编译输出为ES模块,让TS生成与ES import兼容的导出语法:

{
  "compilerOptions": {
    "outDir": "./dist",
    "sourceMap": true,
    "target": "es5",
    "module": "ESNext", // 关键:设置为ES模块格式
    "types": ["node", "jest"],
    "allowJs": true
  }
}

编译后dist/Grid.js会生成ES模块的导出:

export class Grid {
  // ...
}

此时JS文件的import语法可正常使用,但需注意:

  • 浏览器环境下,引入JS文件的<script>标签必须加上type="module"属性:
    <script type="module" src="你的JS文件路径"></script>
    
  • Node环境下,需在package.json中添加"type": "module"。

2. 保持CommonJS输出,修改JS导入方式

若不想调整TS编译配置,JS文件需改用CommonJS的require语法:

const { Grid } = require("./dist/Grid.js");

⚠️ 注意:这种方式仅适用于Node环境,浏览器原生不支持require,需额外加载器支持。


三、使用Webpack打包工具的配置

1. 安装依赖

npm install webpack webpack-cli ts-loader html-webpack-plugin pug-loader html-loader --save-dev

2. 编写Webpack配置文件(webpack.config.js)

const path = require('path');
const HtmlWebpackPlugin = require('html-webpack-plugin');

module.exports = {
  entry: './src/index.js', // 你的入口JS文件路径
  output: {
    filename: 'bundle.js',
    path: path.resolve(__dirname, 'dist'),
    clean: true
  },
  module: {
    rules: [
      // 处理TypeScript文件
      {
        test: /\.ts$/,
        use: 'ts-loader',
        exclude: /node_modules/
      },
      // 处理Pug模板
      {
        test: /\.pug$/,
        use: ['html-loader', 'pug-loader']
      }
    ]
  },
  resolve: {
    extensions: ['.ts', '.js'] // 自动解析后缀
  },
  plugins: [
    // 用Pug模板生成HTML
    new HtmlWebpackPlugin({
      template: './src/index.pug' // 你的Pug模板路径
    })
  ]
};

3. 调整TS配置与打包命令

tsconfig.json保持默认CommonJS或设置为ESNext均可,Webpack会自动处理模块兼容:

{
  "compilerOptions": {
    "outDir": "./dist",
    "sourceMap": true,
    "target": "es5",
    "module": "ESNext",
    "types": ["node", "jest"],
    "allowJs": true
  }
}

在package.json中添加打包脚本:

"scripts": {
  "build": "webpack --mode production"
}

运行npm run build即可生成打包后的文件。


四、Pug与CommonJS的注意事项

  • 变量传递方式:Pug模板向前端JS传递变量时,不要直接在模块内引用Pug变量,需通过全局变量中转:
    script.
      window.pugGlobalVars = {
        demoData: #{yourPugVariable}
      };
    
    然后在JS/TS中通过window.pugGlobalVars访问,避免破坏模块结构。
  • 避免Pug内写CommonJS语法:浏览器原生不支持require,Pug的script标签内不要直接写CommonJS代码,必须通过打包工具处理。
  • 模板模块化:Pug模板拆分使用自身的include/extends语法,与JS模块系统分离,保持职责清晰。

内容的提问来源于stack exchange,提问作者Hugo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.13 18:14:51