简体   繁体   中英

Bundling AngularJS with Webpack, using global node_modules

What I want too archieve: Bundle angularjs application with webpack, but refer to node_modules folder located in a different location on the same filesystem.


  • For this case, lets say my source code of the angular application is located in folder "/source/code".
  • And for the external node modules, located in "/global/npm/App1/node_module"
  • Application name: "App1"

What I have done so far:

  1. Installed the angular application App1 with "npm install -g", so node modules will be located inside App1, in the global npm folder /global/npm/App1
  2. Then I try to bundle App1 from /source/code. This won't work since I am missing node modules, which are located in /global/npm/App1/node_module.

How can I refer to the node modules located in /global/npm/App1/node_module? Do I have to use absolut path for each module I require in webpack.config.js?

I think the feature within Webpack you are looking for is the resolve-modules . This allows you to add additional folders that can be used without the need to add a path into them, almost acting like they are within the node_modules folder.

https://webpack.js.org/configuration/resolve/#resolve-modules

For example

const globalNpm = path.join(__dirname, 'global', 'npm', 'App1', 'node_module'),

resolve: {
        modules: [
            globalNpm
        ]
    }

I find the using path.join make your webpack code more likely to work across platforms (windows, mac, etc). The path in the above example may be wrong as I could really get your folder structure from your question. But the above should allow you require modules directly from your global npm folder.

Please the the above feature is mostly intended for large project and files that could be moved, or reused elsewhere, it stops the need to have

const module = require('../../../a-folder/../../fancycomponent')

On a side note - installing NPM packages globally to be used just within one app is not a normal pattern and can lead to problems, especially with permissions and versioning on local and CI/CD pipelines.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM