Reputation: 1191
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.
Upvotes: 9
Views: 18362
Reputation: 138216
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');
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>
Upvotes: 9