How to conditionally load / bundle CSS files in Meteor 1.0?

后端 未结 1 794
情话喂你
情话喂你 2020-12-18 07:21

I know this question has been asked before but I\'m wondering if something has changed with the advent of 1.0.

I don\'t want Meteor to automatically bundle together

相关标签:
1条回答
  • 2020-12-18 08:03

    You can just put your CSS files somewhere under /public and manually include them from your templates where required. Everything under /public will NOT get bundled, and the URL will have the /public removed e.g.

    1. Create two files: your_meteor_project/public/one.css and ......./two.css. These will be available from your client at http://example.com/one.css (i.e. the "public" does not form part of the URL, it's like the document root for using meteor as a plain old web server).
        meteor create cssSwitcher
        cd cssSwitcher/
        mkdir public
        echo 'html, body { background-color: red; }' > public/one.css
        echo 'html, body { background-color: blue; }' > public/two.css
    
    1. Create a reference to a helper function "appropriateStylesheet" in the head of your HTML :

      HTML template

        <!-- add code to the <body> of the page -->
        <body>
          <h1>Hello!</h1>
          {{> welcomePage}}
        </body>
    
        <!-- define a template called welcomePage -->
        <template name="welcomePage">
          <!-- add code to the <head> of the page -->
          <head>
            <title>My website!</title>
            <link rel="stylesheet" href="/{{appropriateStylesheet}}" type="text/css" />
          </head>
    
          <p>Welcome to my website!</p>
          <button id="red">Red</button>
          <button id="blue">Blue</button>
        </template>
    
    1. Create a helper function.

      JavaScript:

        if (Meteor.isClient) {
          Session.set("stylesheet","red.css"); 
    
          Template.registerHelper("appropriateStylesheet", function() {
            return Session.get("stylesheet");
          });
    
          Template.welcomePage.events({
            'click #blue' : function() { Session.set("stylesheet","two.css"); },
            'click #red'  : function() { Session.set("stylesheet","one.css"); },
          });
    
        }
    

    You can do exactly the same thing with JS files. Put them under /public and meteor ignores them.

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