How can I serve NPM packages using Flask?

后端 未结 3 1297
执笔经年
执笔经年 2020-12-24 12:40

I have a small Flask app which currently sources jQuery and highlight.js from external servers. I\'d like to make these local dependencies which I pull in via NPM.

W

相关标签:
3条回答
  • 2020-12-24 13:11

    You need Bower and you already have NPM. This is all you need to achieve what you want.

    Basically, you will have to create a package.json in the root to install Bower using NPM. Then you will have to create a bower.json to define what all libraries you need, example jQuery.

    Then your flow will be like:

    npm install
    bower install
    

    This will basically install bower for you and the other frontend libraries you defined in bower.json.

    All bower components will go into a directory called bower_components in your root. This is where all your installed bower packages will reside. You can use these packages inside your templates now.

    Also see this to make sure that bower's packages are installed in your static or assets folder which you want to serve.

    0 讨论(0)
  • 2020-12-24 13:22

    maybe a bit late for the answer, but the easiest way to do it is by doing this:

    sudo npm install bower
    echo "bower_components/" >> .gitignore
    bower install -S (here goes whatever you want)
    npm init
    

    Then you fill out the prompt, and you'll have a few new files:

    • bower.json, which is generated by bower to manage dependencies. Using bower install -S (your dependency) will update this file with your new dependencies.
    • package.json, created by npm to manage your project and npm dependencies
    • node_modules, the things you installed with npm
    • bower_components/ which is where all of your front end dependencies live.
    0 讨论(0)
  • 2020-12-24 13:31

    Go to your static folder and there initialize your npm project.

    cd flask_app/static
    $ npm init
    

    after installing and saving npm packages you can serve them like this:

    <script src="{{ url_for('static', filename='node_modules/toastr/toastr.js')}}"></script>
    

    credits to: https://codeburst.io/creating-a-full-stack-web-application-with-python-npm-webpack-and-react-8925800503d9

    0 讨论(0)
提交回复
热议问题