I want to use anime.js. For install this library i need to do this:
- $ npm install animejs --save
- const anime = require('animejs');
I want to writte the code in a js file named "anime.js"
This is "anime.js"
const anime = require('animejs');
anime({
targets: '.animeTest',
translateX: 250,
rotate: '1turn',
backgroundColor: '#FFF',
duration: 800
});
and this is app.js
const express = require('express')
const app = express()
//EJS Layouts
const expressLayouts = require('express-ejs-layouts')
//EJS
app.set('view engine', 'ejs')
app.use(express.static('public'))
app.use(expressLayouts)
app.get('/', (req, res)=>{
res.render('inicio')
})
app.listen(3000,()=>{
console.log('Servidor iniciado. Puerto: 3000')
})
The problem is that when i run the program it tells me
Uncaught ReferenceError: require is not defined
at anime.js:1:15
CodePudding user response:
When I used animejs as a library for a group project, we just included it in the index.html before any other scripts we were trying to run.
Here is the script. Just make sure to include it either in the head with all the meta tags, or somewhere in the body before any of the other scripts you are trying to run.
<script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha512-z4OUqw38qNLpn1libAN9BsoDx6nbNFio5lA6CuTp9NlK83b89hgyCVq N5FdBJptINztxn1Z3SaKSKUS5UP60Q==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
CodePudding user response:
NodeJS and the browser are very different environments. In NodeJS, you can import CommonJS modules by using require
, just as you did. But if you want to run the same code in the browser, you need to use a Bundler. It is true that modern browsers now support import
/export
syntax, which is the new standard for both Node and the browser, but overall it is recommended to bundle all of the files into one.
For your case, if you want an easy solution to your problem and don't want to deal with complicated configuration files, you can try Parcel and keep roughly the same code. Simply navigate to your project directory, and run the following:
$ npx parcel build anime.js
Then simply replace your script with the new, bundled file.