Using third-party libraries in a Marko.js project is quite straightforward. Marko.js allows you to include external JavaScript or CSS libraries in your templates just like in any other HTML-based project. Here's how you can do it:
1. Install the Library
First, you need to install the desired third-party library using npm. For example, let's say you want to use the lodash
library:
npm install lodash
2. Import the Library in Your Template
Once installed, you can import the library in your Marko template by adding a <script>
tag in the <head>
section of your layout or page template. For example, to use lodash
, you can do:
<layout-use template="../../layouts/main.marko">
<layout-put into="title">My Marko App</layout-put>
<layout-put into="head">
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>
</layout-put>
<layout-put into="body">
<!-- Your content here -->
</layout-put>
</layout-use>
3. Use the Library in Your JavaScript Code
Once imported, you can use the library in your Marko template's JavaScript code. For example, using lodash
:
<layout-use template="../../layouts/main.marko">
<layout-put into="title">My Marko App</layout-put>
<layout-put into="head">
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>
</layout-put>
<layout-put into="body">
<script>
// Example usage of lodash
const numbers = [1, 2, 3, 4, 5];
const sum = _.sum(numbers);
console.log('Sum:', sum);
</script>
</layout-put>
</layout-use>
4. Bundle the Library with a Build Tool (Optional)
If you're using a bundler like Webpack or Browserify in your project, you can install the library as a dependency and then require/import it in your JavaScript code. For example, with Webpack:
const _ = require('lodash');
const numbers = [1, 2, 3, 4, 5];
const sum = _.sum(numbers);
console.log('Sum:', sum);
That's it! You can use third-party libraries in your Marko.js project by importing them in your templates and using them in your JavaScript code. Marko.js doesn't restrict you from using external libraries, so you can leverage the vast ecosystem of JavaScript packages available on npm.