javascript 如何使语法导入与电子、 typescript 兼容?

xtfmy6hx  于 2023-03-16  发布在  Java
关注(0)|答案(1)|浏览(116)

我开始了一个新的电子和 typescript 项目,我建立了这个项目,并得到了一个基本的hello world运行,但我试图添加一个库(https://github.com/benjamn/recast),导入语法不工作。

import React from 'react'; // Works
import { parse, prettyPrint } from 'recast'; // Does not work, cannot read property parse of undefined
import tsParser from 'recast/parsers/typescript'; // Does not work
// const recast = require('recast'); // Works
// const tsParser = require('recast/parsers/typescript'); // Works

我的webpack配置和tsconfig如下所示:
webpack.rules.js:

module.exports = [
  // Add support for native node modules
  {
    test: /\.node$/,
    use: "node-loader"
  },
  {
    test: /\.(m?js|node)$/,
    parser: { amd: false },
    use: {
      loader: "@marshallofsound/webpack-asset-relocator-loader",
      options: {
        outputAssetBase: "native_modules"
      }
    }
  },
  {
    test: /\.tsx?$/,
    exclude: /(node_modules|.webpack)/,
    loaders: [
      {
        loader: "ts-loader",
        options: {
          transpileOnly: true
        }
      }
    ]
  }
];

webpack.renderer.config.js:

const rules = require("./webpack.rules");
const plugins = require("./webpack.plugins");
const TsconfigPathsPlugin = require("tsconfig-paths-webpack-plugin");

rules.push({
  test: /\.css$/,
  use: [{ loader: "style-loader" }, { loader: "css-loader" }]
});

module.exports = {
  // Put your normal webpack config below here
  module: {
    rules
  },
  resolve: {
    // Add `.ts` and `.tsx` as a resolvable extension.
    extensions: [".ts", ".tsx", ".js"],
    plugins: [
      new TsconfigPathsPlugin({
        /*configFile: "./path/to/tsconfig.json" */
      })
    ]
  },
  plugins: plugins
};

tsconfig.json:

{
  "compilerOptions": {
    "target": "es6",
    "lib": ["dom", "dom.iterable", "esnext"],
    "skipLibCheck": true,
    "esModuleInterop": true,
    "allowSyntheticDefaultImports": true,
    "strict": true,
    "forceConsistentCasingInFileNames": true,
    "module": "esnext",
    "moduleResolution": "node",
    "resolveJsonModule": true,
    "noEmit": true,
    "jsx": "react",
    "baseUrl": "src/"
  },
  "include": ["src"]
}

我做错什么了吗?

thigvfpy

thigvfpy1#

导入在渲染过程中不起作用,也就是说,它们在前端不起作用。你必须有“松散”的文件,然后作为脚本放在HTML页面上,如:

<script src="./js/script1.js" defer></script>
<script src="./js/script2.js" defer></script>

例如,script1可以包含您需要的定义,用于script2中的某些内容。
我正在研究的另一个选项是使用bundler将脚本及其依赖项全部捆绑到包含该页面所需的所有内容的更大文件中。
要注意的主要事情是,bundler使用commonjs作为输出文件,因为如果我没有记错的话,电子渲染器进程目前只使用commonjs模块。

相关问题