how to use node.js module system on the clientside

前端 未结 7 1049
感情败类
感情败类 2020-11-27 13:48

I would like to use the CommonJS module system in a clientside javascript application. I chose nodejs as implementation but can\'t find any tutorial or docs on how to use no

7条回答
  •  爱一瞬间的悲伤
    2020-11-27 14:11

    Webpack

    I would recommend Webpack which automates node module loading, dependencies, minification, and much more.

    Installation

    To use node modules in your project, first install node.js on your machine. The package management system NPM should be installed along the way. If you have already installed node.js, update Node.js and NPM to the latest version.

    Usage

    Initialization

    Open your project in your code editor and inititialize npm by typing npm init -y to the command line. Next, install webpack locally by typing npm install webpack webpack-cli --save-dev. (--save-dev means these dependencies are added to the devDependencies section of your package.json file which are not required for production)

    Reorder Folder Structure

    Follow the tree structure below to reconstruct your project folder:

    yourProjectName
      |- package.json
      |- /dist
        |- index.html
      |- /src
        |- index.js
    

    Create a dist folder to hold all distribution files and move index.html to that folder. Next, create a src folder for all source files and move your js file to that folder. You should use the exact same file and folder names as appeared in the tree structure. (these are the default of Webpack but you can configure them later by editing webpack.config.js)

    Refactor dependencies

    Remove all before the tag. To import other node modules, add import statements at the beginning of your index.js file. For example, if you want to import lodash, just type import _ from 'lodash'; and proceed to use the _ in your index.js file.

    NOTE: Don't forget to first install the node package first before importing it in JS. To install lodash locally, type npm install lodash. Lodash will be automatically saved to your production dependencies in package.json

    Run Webpack

    Finally, run webpack by typing npx webpack in your command line. You should see main.js generated in the dist folder for you by Webpack.

    Additional resources

    The above guide provides only the most basic way to use Webpack. To explore more useful use cases, go to the official tutorial of Webpack. It provides extremely comprehensive tutorials on topics such as asset management, output management, guides for development and production, etc.

    Reference

    https://webpack.js.org/guides/getting-started/

提交回复
热议问题