包含Node.JS(vue)的文件

A. *_*Lau 6 javascript node.js vue.js vuejs2

所以我想知道如何包含另一个JavaScript文件.很像PHP的include函数/关键字.我不是在寻找这个export功能,因为它只允许你使用其他文件中的变量.

我正在使用vue init webpack my-project.

这是我基本上拥有的(Vue):

mounted () {
    socket = io("http://localhost:8081")
    socket.connect()

    // ensure server has actually put us in a room
    socket.on("find game", () => {
        this.gameSearch = "finding"
    })
    ...
}
Run Code Online (Sandbox Code Playgroud)

所以基本上我有一大堆socket.on我想进入另一个文件.我想知道如何能够将它们包含在原样中以便它们可以像代码已经插入那样工作(就像PHP一样include)


它最终会是什么样子:

mounted () {
    <socket.js file>
}
Run Code Online (Sandbox Code Playgroud)

socket.js

socket = io("http://localhost:8081")
socket.connect()

// ensure server has actually put us in a room
socket.on("find game", () => {
    this.gameSearch = "finding"
})
...
Run Code Online (Sandbox Code Playgroud)

Har*_*iya 5

我知道你提到你不需要导出,你想要内联代码,但我认为你不能轻易地实现这一点,但是如果你现在使用bable和es6作为vue js,你可以导出和导入.

但我保证你不会像你想的那样复杂.{而不是使它内联将会有更多的开销}(它只是我的观点,你可能想要它有一个很好的理由:))

因为最后所有的代码都会在里面 bundle.js

也许它可以很简单,你只需将所有的coed包装到一个大函数中将它与主实例绑定,现在整个代码块看起来就像它在你的主文件里面但仍然在另一个文件中.

我假设您需要在es6,bable和import中使用它

例如:假设code.js和我main.js在同一级别,(main.js)代码的某些部分是巨大的,如事件监听器等,所以我可以在code.js中移动它

code.js /就像你的 socket.js

const code = function() {

    // this whole space is your's

    console.log(this);

    console.log(this.socket);

    const test = () => {
        console.log(this);
    }

    test()
}
export default code
Run Code Online (Sandbox Code Playgroud)

现在我的main.js/就像你的主要vue应用程序

import socketCode from './code';

const main = {
    socket: 'test',
    init() {
        console.log(this);
        let socketCodebinded = socketCode.bind(this); // magical this binding
        socketCodebinded(); // this will do all event-binding things 
        //and good thing is that it will have "this" as context so no breaking of references

        ... continue other code or add another lib ;) like above
    }
}

main.init();
Run Code Online (Sandbox Code Playgroud)

你也可以检查引用/范围以及所有东西都工作正常,你可以在code.js/socket.js文件中堆叠你的所有代码,就像它在main.js里面一样.


Ser*_*evi 2

您可能正在寻找export default. 它将允许您导出函数或对象。

export default {
    // anything
}
Run Code Online (Sandbox Code Playgroud)

在此处查看更多示例:https ://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export