简体   繁体   中英

Import static .js in Vue-cli + webpack

I've been using vue-cli since some time now, and still have not fully understood how file loading is done. I've read documentation and some blogs and helped me to deal with it since now.

I'd like to import static .js files with some constants in a component. I don't want them to be bundled at deployment, so they can be found and changed easily, directly in the server if needed without having to rebuild the whole project.

I tried to place them in /public/constants/foo.js directory and point to them using absolute paths in different ways

import FOO from '/constants/foo.js';  // Not working

const FOO = require('/constants/foo.js');  // Not working

How can I achieve this?

If I understand well your project arch is like

/root
  |__/public
  |     |__/img
  |     |__/css
  |     |__/constants
  |            |__/foo.js
  |            |__/bar.js
  |__/webpack.config.js

In your webpack.config.js create a new entry like

module.exports = {
  entry: './public/index.js'
};

Then create a index.js file inside your public directory and import your foo.js

import foo from './constants/foo';

Of course your foo.js should export something like

export default function foo() {
  //
}

Hoping that will help you.

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