使用Laravel Mix将模板文件/存根编译为JS变量

4

我有一个文件夹/resources/js/stubs。在该文件夹中有几个文件,比如说User.stubController.stubMigration.stub。我想通过以下方式在我的Javascript中使用这些文件的内容:

import Templates from './Templates.js'
console.log(Templates.User)
// The content of User.stub is printed

我不想采用这种方法。
module.exports = name => `
...
`

我也可以使用后端将文件加载到视图中,但我不想这样做。

那么这就需要进行预处理。我能用Laravel Mix进行预处理吗?如果不能,我有哪些选择,需要添加什么到我的Laravel应用程序中?


2
你可能想要使用原始加载器 https://webpack.js.org/loaders/raw-loader/ - Diogo Sgrillo
1个回答

0

部分解决方案

感谢Diogo Sgrillo在评论中指出了这个解决方案。

安装raw-loader yarn add raw-loader --dev

webpack.mix.js

添加以下配置(在我的情况下,所有文件都将以 .stub 扩展名命名):

mix.webpackConfig({
  module: {
    rules: [
      {
        test: /\.stub$/i,
        use: 'raw-loader',
      },
    ],
  },
});

还要在webpack.mix.js中添加一个单独的管道,像这样:

mix.js('src/templates/index.js', 'src/templates.js')

它将编译 index.js 文件中的模板列表,并将它们放入 templates.js 中。

src/templates/index.js

// Dynamically load all stubs using raw-loader (see webpack.mix.js)
let stubs = require.context('./', true, /\.stub$/i);

// Create a object with the filename as key and content as value
exports.stubs = stubs.keys().reduce((result, key) => {
    return {
        [key.replace(/\.\//,'').replace(/\.stub$/,'')] : stubs(key).default,
        ...result
    }
}, {});

export default { /* dont remove this export default or it will break !?? */}

稍后可以这样使用:

let templates = require('./templates.js')
console.log(templates['User.php'])

请在下方评论或添加另一个答案,以了解如何更顺畅地完成此操作。`exports/export`有什么区别?我不能使用`import`方法,只能使用`require`方法,并且如果我尝试使用`export default`(或删除`export default`),它就会中断。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接