简体   繁体   中英

Including npm packages in Vue.js app

I have a vue app that is structured like so (auto created by vue init webpack myProject :

index.html
components/
-main.js
-App.vue

I want to be able to include npm packages. For example, https://github.com/ACollectionOfAtoms/atomic-bohr-model . Following the instructions, I ran npm install atomic-bohr-model --save and included

<script type="text/javascript" src="./node_modules/atomic-bohr-model/dist/atomicBohrModel.min.js" charset="utf-8"></script>

in my index.html file. To use the package, according to the github page, I need to run some javascript,

var atomicConfig = {
  containerId: "#bohr-model-container",
  numElectrons: 88,
  idNumber: 1
}

var myAtom = new Atom(atomicConfig)

that runs with a corresponding element: <div id="bohr-model-container"></div> . So I did the following inside one component that renders into App.vue:

<template>
    <div id="bohr-model-container" style="width: 200px; height: 200px"></div>
</template>

<script>
var atomicConfig = {
    containerId: '#bohr-model-container',
    numElectrons: 88,
    idNumber: 1,
};

var myAtom = new Atom(atomicConfig);

export default {
    name: 'myComponent'
};
</script>

The problem is, when I try to run the app, I get a blank white page. The line, var myAtom = new Atom(atomicConfig); , breaks the application. Why does this happen? My guess is that Atom isn't defined in my component's script. Do I import something in the first line?

Why doesn't this work just like the sample application given for the npm package, that runs just using plain html and js files? Forgive my inexperience, I'm new to javascript frameworks. Thank you in advance.

Generally, to import npm modules in a Webpack project, npm-install the package, and then import or require the module in your code. For example:

import _ from 'lodash';
// OR
const _ = require('lodash');

demo

In your case, atomic-bohr-model only declares window.Atom and does not export any symbols, so you'd need to import it like this:

import 'atomic-bohr-model/dist/atomicBohrModel.min.js'; // sets window.Atom
// OR
require('atomic-bohr-model/dist/atomicBohrModel.min.js'); // sets window.Atom

And then your component would use window.Atom within the mounted lifecycle hook , at which point the template would be rendered and #bohr-model-container would be available:

<template>
  <div id="bohr-model-container" style="width: 200px; height: 200px"></div>
</template>

<script>
import 'atomic-bohr-model/dist/atomicBohrModel.min.js';

export default {
  mounted() {
    new window.Atom({
      containerId: '#bohr-model-container',
      numElectrons: 88,
      // ...
    });
  }
};
</script>

demo

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