Formatting Your npm Modules for AMD

For Liferay DXP to recognize your npm modules, they must be formatted for the Liferay AMD Loader. Luckily, the liferay-npm-bundler handles this for you, you just have to provide the proper configuration and add it to your build script. This article shows how to use the liferay-npm-bundler to set up npm-based portlet projects.

Follow these steps to configure your project to use the liferay-npm-bundler:

  1. Install NodeJS >= v6.11.0 if you don’t have it installed.

  2. Navigate to your portlet’s project folder and initialize a package.json file if it’s not present yet.

    If you don’t have a portlet already, create an empty MVC portlet project. For convenience, you can use Blade CLI to create an empty portlet with the mvc portlet blade template.

    If you don’t have a package.json file, you can run npm init -y to create an empty one based on the project directory’s name.

  3. Run this command to install the liferay-npm-bundler:

    npm install --save-dev liferay-npm-bundler
    
  4. Add the liferay-npm-bundler to your package.json’s build script to pack the needed npm packages and transform them to AMD:

    "scripts": {
          "build": "liferay-npm-bundler"
    }
    
  5. Configure your project for the bundler, using the .npmbundlerrc file (create this file in your project’s root folder if it doesn’t exist). See the liferay-npm-bundler’s .npmbundlerrc structure reference for more information on the available options. Specify the loaders and rules to use for your project’s source files. The example below processes the JavaScript files in the project’s /src/ and /assets/ folders with Babel via the babel-loader:

    {
      "sources": ["src", "assets"],
      "rules": [
        {
          "test": "\\.js$",
          "exclude": "node_modules",
          "use": [
            {
              "loader": "babel-loader",
              "options": {
                "presets": ["env"]
              }
            }
          ]
        }
      ]
    }
    
  6. Run npm install to install the required dependencies.

  7. Run the build script to bundle your dependencies with the liferay-npm-bundler:

    npm run-script build
    

Great! Now you know how to use the liferay-npm-bundler to bundle your npm-based portlets for the Liferay AMD Loader.

« Using npm in Your PortletsMigrating a liferay-npm-bundler Project from 1.x to 2.x »
¿Fue útil este artículo?
Usuarios a los que les pareció útil: 0 de 0