简体   繁体   中英

Webpack code splitting breaks jest import with vueJs components

Jest is throwing an error when trying to load a vueJs component that has dynamic import code.

Component:

<script>
    const Modal = () => import(/* webpackChunkName: "Modal" */ "../pages/common/Modal.vue");

    export default {
        name: "TileEditModal",
        components: {
            Modal
        },
        data() {
            return 
        },
        methods: {
            test() {
                return true;
            }
        }
    }
</script>

Test:

import TileEditModal from "./TileEditModal.vue"

Even with no test running, just importing that component will throw the following error:

  return import( /* webpackChunkName: "Modal" */"../pages/common/Modal.vue");
           ^^^^^^
SyntaxError: Unexpected token import

  at ScriptTransformer._transformAndBuildScript (node_modules/jest-runtime/build/ScriptTransformer.js:289:17)
  at Object.<anonymous> (srcVue/pages/landing/TileEditModal.vue.test.js:3:22)

I've tried this solution but it has not worked for me.

I'm using jest-vue-preprocessor with jest:

  "jest": {
    "moduleFileExtensions": [
      "js",
      "vue"
    ],
    "transform": {
      "^.+\\.js$": "<rootDir>/node_modules/babel-jest",
      ".*\\.(vue)$": "<rootDir>/node_modules/jest-vue-preprocessor"
    },
    "clearMocks": true,
    "resetMocks": true,
    "resetModules": true
  },

I have also tried adding env.test preset to babel:

{
    "presets": [
      "es2015",
      "stage-2",
      "stage-0"
    ],
    "env": {
      "test": {
        "presets": [
          "es2015",
          "stage-2",
          "stage-0"
        ]
      }
    } 
  }

So far nothing works, any ideas? I really want to get this code splitting to work on individual components.

The solution that worked for me was to use the dynamic import babel plugin but also run jest without cache.

jest --no-cache

Unfortunately running it with cache again after that still fails the test so am not sure what's going on, but it works if I leave --no-cache . Just makes the tests slower.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM