2

I installed vuejs with a npm install in my assets/ folder and I created a list_show.js file in priv/static/js/list_show.js . When I do import Vue from "vue" in my list_show.js, it doesn't work and I get this message in the console: "Uncaught SyntaxError: Unexpected identifier".

How can I import modules in my static/js/ folder? (I'm using Phoenix 1.4 and Webpack by default)

popo63301
  • 509
  • 1
  • 4
  • 10
  • Answered here: https://stackoverflow.com/a/43265955/1173020 It's not about Vue, but it shouldn't be a big problem to add Vue too. – denis.peplin Feb 24 '19 at 15:58
  • Sorry, I don't see how I can add vueJS with your answer. Also, I don't think it would be practical to always call "webpack.ProvidePlugin" for every single node modules I'm installing. – popo63301 Feb 24 '19 at 16:12
  • are you using babel with webpack, or how are you transpiling the es6 syntax? – webdeb Feb 25 '19 at 20:46
  • I'm using the basic configuration of Phoenix 1.4. Meaning webpack – popo63301 Feb 25 '19 at 20:52

1 Answers1

1

You should not create your .js files in the /priv/static/js directory. Instead, use the /assets directory.

Phoenix 1.4 uses Webpack to bundle js files located in /assets into a single app.js file which will be placed into /priv/static/js. As an entry point to your application, you can use /assets/js/app.js where the following lines load Vue:

import Vue from 'vue';

new Vue({
  // ...
});

(You can also put this code in a seperate .js file, as long as you import it in app.js)

This solution, however, won't help if you need static js files for different routes. You maybe want to always render priv/static/js/app.js, but specific files just on specific layouts. Achieving multiple output files in priv/static/js can be done by modifying your webpack.config.js slightly and adding more entrypoints:

entry: {
  app: ['./js/app.js'].concat(glob.sync('./vendor/**/*.js')),
  special: ['./js/special.js']
},
output: {
  filename: '[name].js',
  path: path.resolve(__dirname, '../priv/static/js')},
}

With this config, two files will be created:

  • priv/static/js/app.js - Containing all vendor files and app.js
  • priv/static/js/special.js - Containing just special.js

The special.js file can be included within Phoenix then:

 <script type="text/javascript" src="<%= Routes.static_path(@conn, "/js/special.js") %>"></script>
Jonas Dellinger
  • 1,294
  • 9
  • 19