【问题标题】:Vue & webpack & typescript "Cannot access '__WEBPACK_DEFAULT_EXPORT__' before initialization"Vue & webpack & typescript“初始化前无法访问'__WEBPACK_DEFAULT_EXPORT__'”
【发布时间】:2021-07-05 21:10:02
【问题描述】:
// webpack.config.js
const path = require('path');
const MiniCssExtractPlugin = require('mini-css-extract-plugin');
const LicenseWebpackPlugin = require("license-webpack-plugin").LicenseWebpackPlugin;
const webpack = require('webpack');
const { VueLoaderPlugin } = require('vue-loader');

module.exports = (env, { mode }) => ({
  entry: './src/main.ts',
  module: {
    rules: [
      {
        test: /\.vue$/,
        loader: 'vue-loader'
      },
      {
        test: /\.ts$/,
        use: 'ts-loader',
        exclude: /node_modules/,
      }, {
        test: /\.s[ac]ss$/i,
        use: [MiniCssExtractPlugin.loader, 'css-loader?url=false', 'sass-loader']
      }
    ],
  },
  resolve: {
    extensions: [ '.vue', '.ts', '.js' ],
  },
  output: {
    filename: 'index.js',
    path: path.resolve(__dirname, 'static'),
  },
  plugins: [
    new MiniCssExtractPlugin({ filename: 'index.css' }),
    new LicenseWebpackPlugin({
      outputFilename: 'licenses.txt'
    }),
    new webpack.DefinePlugin({
      'process.env.DEVELOPMENT': `${mode === "development"}`
    }),
    new VueLoaderPlugin()
  ],
  watchOptions: {
    aggregateTimeout: 200,
    poll: 1000
  }
});
// main.ts
import Vue from 'vue';
import App from './App.vue';
console.log(App);
<template>
    <div>
        HI
    </div>
</template>

<script lang="ts">
import Vue from 'vue';

export default Vue.extend({
    components: {}
});
</script>

<style lang="sass">
</style>

我使用 webpack 编译 vue & typescript 代码。 Webpack 编译所有代码没有任何错误,但在运行时,App.vue 中的某些内容会出错。

如果我将lang="ts" 属性添加到我的单个文件组件中的脚本标记,则会产生错误Uncaught ReferenceError: Cannot access '__WEBPACK_DEFAULT_EXPORT__' before initialization。没有这个选项,它工作得很好。

我该如何解决这个问题?

【问题讨论】:

    标签: typescript vue.js webpack


    【解决方案1】:

    我刚刚遇到了同样的问题,经过几个小时的谷歌搜索,我终于在 Vue 文档的 corner 中找到了解决方案。

    基本上,您需要在 webpack 配置中添加一个额外的 appendTsSuffixTo 选项。

    module.exports = {
      ...
      module: {
        rules: [
          {
            test: /\.tsx?$/,
            loader: 'ts-loader',
            options: {
              appendTsSuffixTo: [/\.vue$/],
            },
            exclude: /node_modules/,
          },
          {
            test: /\.vue$/,
            loader: 'vue-loader',
          }
    

    【讨论】:

      猜你喜欢
      • 2021-03-10
      • 2022-12-10
      • 2021-01-31
      • 2020-08-25
      • 2020-09-08
      • 2021-09-29
      • 2019-10-12
      • 2020-11-30
      • 2021-11-02
      相关资源
      最近更新 更多